JavaScript Coding Style
Tags: javascript, codenewbie, webdev, tutorial
Published: 2021-02-02 22:09:23

{% youtube rR2Th1aqc-s %}

---

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.

```js
if (condition) {
    // statements
}
```

---
### 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:

```js
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.
`
```

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:

```js
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 ;
```

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

```js
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);
```

**A better practice is to use a rest parameter (`...para`) when necessary** - we will see that in a [different article](https://dev.to/bello/javascript-rest-parameters-and-spread-syntax-5bpm#rest-parameter). See below:

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

peopleGrades(2, 4, 5, 2, 8, 2);
```

Besides rest operators, there's also a spread operator! -  we will see that in a [different article](https://dev.to/bello/javascript-rest-parameters-and-spread-syntax-5bpm#spread-syntax).

---
### Vertical Indents
Insert extra newlines to divide logical blocks like in function scope.

```js
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
```
*There should not be more than nine lines of code without a vertical indentation*.

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

```js
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) );
```

> 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:

```js
alert("There will be an error")

[1, 2].forEach(alert)
```

---
<a href="https://www.whogohost.com/host/aff.php?aff=7390&page=hosting" target="_blank"><img src="https://www.whogohost.com/images/affiliates/unlimited-hosting-728-x-90.png" /></a>

---

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](https://standardjs.com/).

**Debugged example above**:
```js
alert("There will be no error");

[1, 2].forEach(alert);
```

---
### Nesting Levels
Try to avoid many nesting levels when necessary. Use the `continue` statement to avoid extra nesting when applicable.

```js
for (let i = 0; i <10; i++) {
  if (condition) {
    // new nesting level
  }
}
```

We can reduce the nesting level above. See below:

```js
for (let i = 0; i <10; i++) {
  if (!condition) continue;
    // no nesting level
}
```

See another example below:

**More nesting levels**:

```js
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³
```

**Lesser nesting levels**:

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

  let result = 1;

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

    return result;
  }
}
```

---
### 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:

-  [Google JavaScript Style Guide](https://google.github.io/styleguide/jsguide.html) ;
-  [Airbnb JavaScript Style Guide](https://github.com/airbnb/javascript) ;
-  [Idiomatic.JS](https://github.com/rwaldron/idiomatic.js) ;
-  [StandardJS](https://standardjs.com/) ;
- And many more...

---
### 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:

 - [JSLint](http://www.jslint.com/);
 - [JSHint](http://www.jshint.com/);
 - [ESLint](http://eslint.org/) – more popular.

> Most editors already have linting tools enabled by default ([NodeJS](https://nodejs.org/) installation required).

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

**Happy Coding!!!**

---
[![Buy me a Coffee](https://res.cloudinary.com/bizstak/image/upload/v1610317510/ko-fi-trans_fr3su4.png)](https://www.buymeacoffee.com/techstackmedia)

---
### 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.

<a href="https://domain.mno8.net/c/2653712/848391/9560" target="_top" id="848391"><img src="//a.impactradius-go.com/display-ad/9560-848391" border="0" alt="" width="300" height="250"/></a><img height="0" width="0" src="https://imp.pxf.io/i/2653712/848391/9560" style="position:absolute;visibility:hidden;" border="0" />