DEV Community

Cover image for JavaScript Coding Style
Bello Osagie
Bello Osagie

Posted on • Edited on

JavaScript Coding Style


Code style is the art of programming to make code more readable and clean.
Below are the rules and reasons for code styles:


Curly braces

Curly braces signify where a scope starts and end. There should always be a space between curly braces and keywords, closing parentheses or characters.

if (condition) {
    // statements
}
Enter fullscreen mode Exit fullscreen mode

Line Length

Lengthy code spanning an entirely new line is a bad practice. It is advisable to break or split such code into multiple lines for readability at a glance.

See the example below:

const str = `
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Unde soluta 
nihil consequatur minima rem officiis hic dignissimos dolorem quae 
nemo accusamus consequuntur, quos quibusdam asperiores a ad 
totam sunt id.
`
Enter fullscreen mode Exit fullscreen mode

The number of characters (including spaces) in a single line should not exceed 79 characters. Check the col (column) mostly at the bottom of a text editor to get the length of characters.

For multiple parameters in functions or conditions in a loop, the rule extends to them. Rest parameter is recommended for more than three parameters when necessary.

Lengthy code in a single line (line 1) is a bad practice. See below:

const peopleGrades = (index, para1, para2, para3, para4, para5) => {
  const names = [ para1, para2, para3, para4, para5 ];
  return names[index];
}

peopleGrades(2, 4, 5, 2, 8, 2) // 2 ;
Enter fullscreen mode Exit fullscreen mode

Lengthy code broken multiple lines is good practice. See below:

const peopleGrades = (index, 
                     para1, 
                     para2, 
                     para3, 
                     para4, 
                     para5
                    ) => {
  const names = [ para1, para2, para3, para4, para5 ];
  return names[index];
}

peopleGrades(2, 4, 5, 2, 8, 2);
Enter fullscreen mode Exit fullscreen mode

A better practice is to use a rest parameter (...para) when necessary - we will see that in a different article. See below:

const peopleGrades = (index, ...para) => {
  const names = [ ...para ];
  return names[index];
};

peopleGrades(2, 4, 5, 2, 8, 2);
Enter fullscreen mode Exit fullscreen mode

Besides rest operators, there's also a spread operator! - we will see that in a different article.


Vertical Indents

Insert extra newlines to divide logical blocks like in function scope.

function add3s(x, y) {
  let result = 10;
  // empty new line
  for (let i = 0; i <= y; i++) {
    result += x;
  }
  // empty new line
  return result
}

console.log( add3s(3, 2) ); // 19
Enter fullscreen mode Exit fullscreen mode

There should not be more than nine lines of code without a vertical indentation.

If you are wondering how we got 19, see below:

function add3s(x, y) {
  let result = 10;

  for (let i = 0; i <= y; i++) {
    result += x;  // result = result + x
    // result(i0) = result + 3 => 13 
    // result(i1) = result + 3; => result(i0) + 3 = 16 
    // result(i2) = result + 3; => result(i1) + 3 = 19
  } 

  return result;
  // result(y) = result + 3; => 19 
}

console.log( add3s(3, 2) );
Enter fullscreen mode Exit fullscreen mode

Hint: Inner scope is reachable to their immediate outer scope (and global scope). That is why the result in the for loop reaches its value, 10 for each iteration (i₀ to i₂).


Semicolons

Code will run perfectly well most of the time without semicolons, but you may never know when statements without semicolons can lead to bugs (errors). That is, automatic semicolon insertion fails sometimes.

See the example below:

alert("There will be an error")

[1, 2].forEach(alert)
Enter fullscreen mode Exit fullscreen mode


For a script containing complex codes in between the code below, you will agree that it will difficult to trace the error.

Experienced JavaScript programmers may omit semicolons by importing modules to the script file like configuring with StandardJS.

Debugged example above:

alert("There will be no error");

[1, 2].forEach(alert);
Enter fullscreen mode Exit fullscreen mode

Nesting Levels

Try to avoid many nesting levels when necessary. Use the continue statement to avoid extra nesting when applicable.

for (let i = 0; i <10; i++) {
  if (condition) {
    // new nesting level
  }
}
Enter fullscreen mode Exit fullscreen mode

We can reduce the nesting level above. See below:

for (let i = 0; i <10; i++) {
  if (!condition) continue;
    // no nesting level
}
Enter fullscreen mode Exit fullscreen mode

See another example below:

More nesting levels:

function pow(x, n) {
  if (n < 0) {
    console.log("🤔");
  } else {
    let result = 1;

    for (let i = 0; i < n; i++) {
      result *= x;
    }

    return result;
  }
}

pow(2, 3); // 8 => 2³
Enter fullscreen mode Exit fullscreen mode

Lesser nesting levels:

function pow(x, n) {
  if (n < 0) {
    console.log("🤔");
    return;
  }

  let result = 1;

  for (let i = 0; i < n; i++) {
    result *= x;

    return result;
  }
}
Enter fullscreen mode Exit fullscreen mode

Helper functions

Helper functions make code more readable. Use them when necessary.


Style Guides

There are more general rules to properly style code. Especially when working in a team, a consistent uniform code is a best practice.

See the list below:


Automated Linters

Linters are tools that automatically check code styles to make improvement suggestions.

It also checks bugs, like typos in variable or function names.

Here are some well-known linting tools:

Most editors already have linting tools enabled by default (NodeJS installation required).

Also, certain IDEs have built-in linting, which is convenient but not as customizable as ESLint.

Happy Coding!!!


Buy me a Coffee


TechStack Media | Domain

  • Purchase a .com domain name as low as $9.99.
  • Purchase a .net domain name as low as $12.99.
  • Get cheaper domain names as low as $3.
  • Build a website with ease.

Top comments (0)