Skip to main content

Introducing ESLint: A Guide to Cleaner JavaScript Code

What is ESLint?​

ESLint is a static code analysis tool that identifies problematic patterns in JavaScript code.

Airbnb’s JavaScript Style Guide​

Airbnb JavaScript style guide is popular by using Airbnb’s ESLint configuration.

Here are some rules it mentioned:

  • Use the literal syntax for object creation.
// bad
const item = new Object();

// good
const item = {};
  • Use single quotes '' for strings.

  • Use === and !== over == and !=.

  • Use const for all of your references; avoid using var. If you must reassign references, use let instead of var.

  • Arrow Functions

// bad
[1, 2, 3].map(function (x) {
const y = x + 1;
return x * y;
});

// good
[1, 2, 3].map((x) => {
const y = x + 1;
return x * y;
});
  • Destructuring
// bad
function getFullName(user) {
const firstName = user.firstName;
const lastName = user.lastName;

return `${firstName} ${lastName}`;
}

// good
function getFullName(user) {
const { firstName, lastName } = user;
return `${firstName} ${lastName}`;
}

// best
function getFullName({ firstName, lastName }) {
return `${firstName} ${lastName}`;
}


Setting Up ESLint with Airbnb’s Style Guide​

First, install ESLint as a development dependency:

npm install eslint --save-dev

Then, initialize a default ESLint configuration:

npx eslint --init

To adopt Airbnb’s style guide, install the Airbnb configuration package:

npx install-peerdeps --dev eslint-config-airbnb

Then, in your .eslintrc.js file, extend Airbnb’s configuration:


module.exports = {
"extends": "airbnb",
};

Now, we can lint our code according to Airbnb’s style guide using the eslint command.