Skip to content

JavaScript Code Etiquette

Fullchee Zhang edited this page Dec 27, 2018 · 21 revisions

JavaScript Coding Style Guide

TODO: Create an ESLint configuration that will satisfy these conditions

if blocks/braces

If blocks should be of the form

if (condition) {
    ...
} else {
    ....
}

'use strict';

The use strict statement at the top of a function is absolutely necessary. The use-strict statement lies underneath the function declaration, and has a blank line following it. It tells the compiler not to be lenient with the JavaScript code, which can be the first line of defence against syntactically incorrect or buggy code.

var

  • No implicit var declarations.
    • ie: use var (or const or let) when declaring a variable
  • No duplicate variable declarations or shadowing.
  • Declare variables at the top of the function, after the aforementioned use-strict's following blank line.

Semicolons

  • Always use semicolons. The JavaScript engine has the ability to infer semicolons, but omitting them is frowned upon.

Spacing in equations

  • Spacing in equations is necessary. var x=2+2*65/2 < var x = 2 + 2 * 65 / 2.

Parenthesis in equations

  • Keep in mind that parenthesis might help future programmers read your equations. Let's take the above example, but add in some more bits. var x = 2 + 2 * 65 / 2^3 + 65 / 3 is a bit of an eyeful (maybe not the best case, but it can get the point across). Try simplifying it for the reader like: var x = 2 + ((2 * 65) / 2^3) + (65 / 3).

Function spacing

  • Put a double space in between function declarations.

Variable naming

  • CONSTANTS_ARE_IN_UPPERCASE.
  • The rest are in camelCase.

jQuery selector caching

  • Duplicated selectors can and often should be cached for efficiency. var circleObject = $("#circle");

Function naming

  • camelCase.
  • Imperative voice (Things such as makeNode())

Line breaking

var x = 1 + 2 + 3 + 
  4;

is preferred over

var x = 1 + 2 + 3
  + 4;

Likewise,

if (i === "i" ||
    i === "j") {
...
}

is preferred over

if (i === "i"
    || i === "j") {
...
}

Quotation marks ##

  • ' is necessary.