JavaScript Style Guide

Last updated: October 21, 2020

Code Style

Code style is extremely important when developing code that you hope to last longer than its first writing. This is especially important with JavaScript because the interpreter is very tolerant and will allow a great deal of syntactic mistakes to pass undetected when code is executed. JS developers must exhibit great discipline in writing idiomatic code that is easily readable to all other developers.

Because of this, we're going to be adhering to a style guide for code written in this class. If you ever go out and write code professionally, you would do well to adhere to a structured style guide as well.

Basics

Indentation: Use spaces, not tabs. 2 or 4 spaces.

Line Length: Avoid lines longer than 100 characters.

Comments: Be generous with comments, but try to describe more about why code is the way it is, and the assumptions it makes, rather than how it does things. JavaScript is an expressive enough language (with first class functions, etc.) that you can write very readable code that expresses intent properly.

Whitespace: Most tokens should be separated by whitespace. Specifically, you should always have a space before and after your infix operators (+, -, &&, etc). Also use whitespace between the function keyword and its arguments:

var parseInt = function (string, radix) {
...
};

if / else blocks and for / while loops should always be split into lines, as per the K&R standard (aka The One True Brace Style):

if (predicate) {
...
} else {
...
}
for (var i = 0; i < len; i++) {
...
}
while (condition) {
...
}

Functions

Functions should generally be declared by assigning to an identifier:

var parseInt = function (string, radix) {
...
};

If you use an identifier with a function expression, it provides the added benefit of showing up with a proper identifier in stack traces but this is not strictly necessary.

var parseInt = function parseInt (string, radix) {
...
};

Do not use a function definition syntax like the following example, because the scoping works slightly differently – this function is "hoisted" to the top of its scope while the above function expression syntax means that a function is only available when its expression is evaluated (and stored to that variable).

// Don't use this syntax!
function parseInt (string, radix) {
...
};

Operators

Do not use the double-equal ==. It does type coercion and is generally recognized as a bad idea.

Do use the triple-equal ===, which does strict equality.

Do not perform assignments in the conditional of if and while statements. It is easy to mistake an assignment like this one...

if (a = b) { ... }

...for an equality check like this one:

if (a === b) { ... }

Do not use eval in your programs. Similarly, do not use the Function constructor or pass strings to setTimeout / setInterval. We'll never ask you to do these weird hacky sorts of things - this class is about encouraging good code.

Do not use bitwise operators (&, |, and ~) in place of logical operators (&&, ||, and !).

Similarly, do not use the with statement.

Do not use the for-in loop for arrays . You can use if for objects, but this isn't necessary either - if you need to iterate over an object's properties, you should probably use Object.keys.

Code Cruft

Do not leave debugging-type functions (like console.log or alert) in your finished code. The obvious exception is in cases where writing to the console, or displaying an alert message, is the intended function of the code.

IIFEs

Finally, you may want to include an Immediately Invoked Function Expression (IIFE) in your JavaScript files to avoid polluting the global namespace - but this is not strictly necessary.

(function() {
// do stuff
module.exports = {
// export stuff
}
})()

ESLint

In order to do ensure that your JavaScript submissions adhere to this style guide, we will be using ESLint. You should definitely check your code style with ESLint before submitting. If you are not following the rules, style points may be deducted.

For each homework, we will provide you with a .eslintrc file, but they will specify the same rules. These are rules used in Airbnb, which are among the best-accepted and most general JavaScript style guidelines.

Here's how to set up the styles on your own.

Create a file called .eslintrc at the root directory. Copy and paste the following rules.

{
"env": {
"browser": true,
"node": true,
"es6": true
},
"extends": "airbnb",
"parser": "babel-eslint",
"rules": {
"brace-style": [2, "1tbs"],
"camelcase": 0,
"no-bitwise": 2,
"no-empty": 2,
"no-ex-assign": 2,
"no-lonely-if": 2,
"no-mixed-spaces-and-tabs": 2,
"no-tabs": 2,
"no-underscore-dangle": 0,
"no-unused-vars": 0,
"quote-props": [2, "as-needed"],
"quotes": [2, "single", "avoid-escape"],
"strict": 0,
"semi": ["error", "never"], // require or disallow use of semicolons instead of ASI,
"arrow-parens": ["error", "as-needed"] // require the use of parenthesis when needed
},
"parserOptions": {
"ecmaVersion": 2017
}
}

The specific definitions for these rules can be found in the ESLint rules documentation. Including them in your final project would probably be a good idea as well - it could save you a great deal of trouble down the line!

Your file structure should now look similar to this.

file hierarchy

In package.json, you should add the following packages

"devDependencies": {
"eslint-plugin-import": "^2.21.2",
"eslint-plugin-jsx-a11y": "^6.3.0",
"eslint-plugin-react": "^7.20.0",
"eslint-plugin-react-hooks": "^4 || ^3 || ^2.3.0 || ^1.7.0",
...
},
"dependencies": {
"eslint": "^6.8.0",
"eslint-config-airbnb": "^18.2.0",
"babel-eslint": "^10.1.0",
...
}

Your package.json should look similar to this

package.json

Make sure you are using VSCode and install the ESLint extension.

eslint-vscode-extension

Now, run npm install in your command-line tools/ terminal. After the installation is complete, open VS Code, and you should be able to see ESLint complaining if you are using bad styles :)

eslint-example