What Is Clean Code and the Implementation in NodeJS

Ardian Ghifari
2 min readApr 14, 2020

A code is clean if it can be understood easily by everyone on the team. Clean code can be read and enhanced by a developer other than its original author. With understandability comes readability, changeability, extensibility and maintainability.

Implementing Clean Code in NodeJS with Linter

Linter is a tool that detects issues in your source code. The history of linter goes way back to 1970s when people start to debug code written in C language. Since then, many developers have created various linters for other programming languages. One of them is eslint that can be used in NodeJS. Eslint can catch various errors, for example:

  1. avoid infinite loops in the for loop conditions
  2. make sure all getter methods return something
  3. check for duplicate cases in switch
  4. check for unreachable code

Basically, Eslint doesn’t have default rules, you can decide which rule that suites your need. In this project, my team uses rule from Airbnb. If you use VSCode, you should install Eslint Extension. This extension will show your mistake in red (for error) and yellow (for warning) squiggly underline and fix your code style on save.

To use Eslint, you have to install it first in the command prompt or terminal using this command:

npm install eslint --save-dev

# create a `.eslintrc` configuration file
./node_modules/.bin/eslint --init

# run ESLint against any file with
./node_modules/.bin/eslint yourfile.js

To install Airbnb configuration package, you can use this command:

npm install --save-dev eslint-config-airbnb

After that, you must add following lines in your .eslintrc file in the root of your project:

{
"extends": "airbnb",
}

To run Eslint, you can use this commands:

npm run lint . # for all files in current directories
npm run lint /path/to/folder/or/file # for selected #directories/files

You can check your code issues there. If you use VSCode terminal, you can ctrl+click the file name to go to the selected file. The tab problem in VS Code terminal also show your mistake in current file.

To fix linter error, you can use this commands:

npm run lint:fix . # for all files in current directories
npm run lint:fix /path/to/folder/or/file # for selected #directories/files

The commands above will automatically fix your issues.

I hope my article can help you understand Clean Code implementation using Eslint. Thank you for reading my article.

Reference:

https://flaviocopes.com/eslint/
My team’s gitlab repository readme file

--

--