Get disciplined with Javascript (or the simplest guide for eslint)

·

3 min read

In my opinion, the worst point of javascript is the lack of formatting. There isn't a specific rule included in the language that allow us to format the code. Therefore, when you work in a team, it is not easy to have the same way of writing. And when you open a pull request you can have diff that can be avoided.

For example, with this 4 lines of code:

for (let i = 0; i < 5; i += 1) 
{
  console.log("i am not equal to 3, got " + i)
}

you can write:

for (let i = 0; i < 5; i += 1) {
  console.log(`i am not equal to 3, got ${i}`);
}

In this 4 lines, we have the following diff:

--- a/my_file.js
+++ b/my_file.js
@@ -1,4 +1,3 @@
-for (let i = 0; i < 5; i += 1)
-{
-  console.log("i am not equal to 3, got" + i);
+for (let i = 0; i < 5; i += 1) {
+  console.log(`i am not equal to 3, got${i}`);
 }

Imagine what would it be if you work in a project containing thousands of lines and in a team of 5-6 developers.

use eslint as a mentor

The purpose of this article is to help you to understand, to install and to use eslint.

I am not here to rewrite what as been already explained. Don't forget to read the documentation.

install and use eslint

I am not going to duplicate what is already done. Follow the steps here.

The use of eslint is really easy. You have a nice and efficiency CLI and a good integration with code editors.

use the cli

The following command is the one I use every hour of my day as a software engineer to check my syntax:

$ npx eslint --cache .

You can add it as a script in package.json with:

{
  "scripts": {
    "lint": "npx eslint --cache ."
  }
}

The first thing to know is the use of npx. Since it is not recommended to globally install eslint, the use of the CLI is done from the binary installed in ./node_modules/.bin.

The second thing you can note is the presence of the --cache option. From the documentation:

--cache  Only check changed files - default: false

By generating a cache that contains the metadata (by default) of the files already checked by eslint, it avoids the redundancy and increases the performance.

Do not forget to add .eslintcache to .gitignore

why not use prettier

prettier is an opinionated code formatter. In a professional team, it is not really recommended to use this kind of tool. The fewer decisions you make, the more time you have to concentrate fully on development.

The best choice is to use a popular guide for eslint (google, airbnb, standard and the latest xojs) that can be used independently, whatever is your environment (for professional or personal projects).

a last word

A code with a good syntax and automated fixes helps to get more concentration about what you really do: creating things.