Code style is extremely important for readability, but also very opinion-based. It's a good idea to install a linter once you're comfortable with Javascript so you can start improving consistency and readability. A linter is a tool that checks your code for common issues (like forgetting let
in a for loop, cough cough) and styling inconsistencies (forgetting indentation).
Eslint is the most popular linter for Javascript. We'll walk you through installing it below.
You only need to do this once because we're installing it globally.
npm install --global eslint eslint-config-airbnb-base eslint-plugin-import@latest
We're installing Airbnb's custom rules, which are one of the top three most popular code 'standards'. I like them because they give justifications for WHY they use each of their rules on their github page.
You only need to do this once per editor.
- If you're using VS Code, you can do that here.
- If you're using Atom, you can do that here.
- If you're using Sublime, follow the "Plugin installation" section here.
You can go crazy with customizing your own rules, but I'd recommend starting with something tried-and-true. I've found Airbnb's rules to be awesome.
To set up a specific set of rules, run eslint --init
. It'll take you through a menu, and you want to select "Use a popular styleguide", then "Airbnb". That will create an .eslintrc
file, which is a configuration file for eslint. You don't really have to mess with it.
You will likely see some new errors pop up in your code; note that these aren't Javascript errors (your code may be valid), but will be linter errors (which just means its not consistently formatted or doesn't follow best practices).