What to consider when writing clean javascript code

Violet kwamboka
2 min readFeb 4, 2021

1. Isolate your code

Have specific chunks of logic (usually functions) separated by topic. If you write a function, the function should default to having only one purpose and should not do multiple things at once.

Also, you should avoid causing side effects, meaning in most cases, you should not change anything that is declared outside your function. You receive data into functions with parameters; everything else should not be accessed. If you wish to get something out of the function, return new values.

2. Modularization

You can group multiple functions into one module (and/or class, if you wish) if these functions are used in a similar way or do similar things. For example, if you have many different calculations to do, split them up into isolated steps (functions) that you can chain. However, these functions can all be declared in one file (module). Here is the example in JavaScript:

function add(a, b) {

return a + b

}

function subtract(a, b) {

return a — b

}

module.exports = {

add,

subtract

}

const { add, subtract } = require(‘./calculations’)

console.log(subtract(5, add(3, 2))

3. Prefer multiple parameters over single object parameters

When declaring a function, you should always prefer multiple parameters over one parameter that expects an object:

// GOOD

function displayUser(firstName, lastName, age) {

console.log(`This is ${firstName} ${lastName}. She is ${age} years old.`)

}

// BAD

function displayUser(user) {

console.log(`This is ${user.firstName} ${user.lastName}. She is ${user.age} years old.`)

}

4. Destructuring

Destructuring is a nice tool that was introduced with ES6. It lets you grab specific fields from an object and assign it to a variable immediately. You can use this for any kind of object or module. It does make sense to only import the functions you need to use in your file instead of the whole module, and then access the specific functions from it. Similarly, when you decide that you definitely need an object as function parameter, use destructuring as well.

// EXAMPLE FOR MODULES

const { add, subtract } = require(‘./calculations’)

5. Use default values

Default values for destructuring or even basic function parameters are very useful. Firstly, they give you an example of what value you can pass to the function. Secondly, you can indicate which values are required and which are not.

7. Line and indentation limit

You should limit your file size to a certain number of lines. I tend to keep my files below 100 lines of code. Sometimes, it is hard to break up files, and they will grow to 200–300 lines and, in rare occasions, up to 400.

--

--