Noura JavaScript Style Guide() {
This style guide is derivation from eslint-config-airbnb-base
Usage
npm info "eslint-config-noura@latest" peerDependencies
If using npm 5+, use this shortcut
npx install-peerdeps --dev eslint-config-noura
If using npm < 5, Linux/OSX users can run
Which produces and runs a command like:
npm install --save-dev eslint-config-noura eslint@^#.#.# eslint-plugin-import@^#.#.#
If using npm < 5, Windows users can either install all the peer dependencies manually, or use the install-peerdeps cli tool.
npm install -g install-peerdepsinstall-peerdeps --dev eslint-config-noura
The cli will produce and run a command like:
npm install --save-dev eslint-config-noura eslint@^#.#.# eslint-plugin-import@^#.#.#
- Add
"extends": "noura"
to your .eslintrc.
Documentations
Table of Contents
- Types
- References
- Objects
- Arrays
- Destructuring
- Strings
- Functions
- Arrow Functions
- Classes & Constructors
- Modules
- Iterators and Generators
- Properties
- Variables
- Hoisting
- Comparison Operators & Equality
- Blocks
- Control Statements
- Comments
- Whitespace
- Commas
- Semicolons
- Type Casting & Coercion
- Naming Conventions
- Accessors
- Events
- jQuery
- ECMAScript 5 Compatibility
- ECMAScript 6+ (ES 2015+) Styles
- Standard Library
- Testing
- Performance
- Resources
- In the Wild
- Translation
- The JavaScript Style Guide Guide
- Chat With Us About JavaScript
- Contributors
- License
- Amendments
Types
-
1.1 Primitives: When you access a primitive type you work directly on its value.
string
number
boolean
null
undefined
symbol
const foo = 1;let bar = foo;bar = 9;console; // => 1, 9- Symbols cannot be faithfully polyfilled, so they should not be used when targeting browsers/environments that don't support them natively.
-
1.2 Complex: When you access a complex type you work on a reference to its value.
object
array
function
const foo = 1 2;const bar = foo;bar0 = 9;console; // => 9, 9
References
-
2.1 Use
const
for all of your references; avoid usingvar
. eslint:prefer-const
,no-const-assign
Why? This ensures that you can’t reassign your references, which can lead to bugs and difficult to comprehend code.
// badvar a = 1;var b = 2;// goodconst a = 1;const b = 2;
-
2.2 If you must reassign references, use
let
instead ofvar
. eslint:no-var
Why?
let
is block-scoped rather than function-scoped likevar
.// badvar count = 1;if truecount += 1;// good, use the let.let count = 1;if truecount += 1;
-
2.3 Note that both
let
andconst
are block-scoped.// const and let only exist in the blocks they are defined in.let a = 1;const b = 1;console; // ReferenceErrorconsole; // ReferenceError
Objects
-
3.1 Use the literal syntax for object creation. eslint:
no-new-object
// badconst item = ;// goodconst item = {};
-
3.2 Use computed property names when creating objects with dynamic property names.
Why? They allow you to define all the properties of an object in one place.
{return `a key named `;}// badconst obj =id: 5name: 'San Francisco';obj = true;// goodconst obj =id: 5name: 'San Francisco': true;
-
3.3 Use object method shorthand. eslint:
object-shorthand
// badconst atom =value: 1{return atomvalue + value;};// goodconst atom =value: 1{return atomvalue + value;};
-
3.4 Use property value shorthand. eslint:
object-shorthand
Why? It is shorter to write and descriptive.
const lukeSkywalker = 'Luke Skywalker';// badconst obj =lukeSkywalker: lukeSkywalker;// goodconst obj =lukeSkywalker;
-
3.5 Group your shorthand properties at the beginning of your object declaration.
Why? It’s easier to tell which properties are using the shorthand.
const anakinSkywalker = 'Anakin Skywalker';const lukeSkywalker = 'Luke Skywalker';// badconst obj =episodeOne: 1twoJediWalkIntoACantina: 2lukeSkywalkerepisodeThree: 3mayTheFourth: 4anakinSkywalker;// goodconst obj =lukeSkywalkeranakinSkywalkerepisodeOne: 1twoJediWalkIntoACantina: 2episodeThree: 3mayTheFourth: 4;
-
3.6 Only quote properties that are invalid identifiers. eslint:
quote-props
Why? In general we consider it subjectively easier to read. It improves syntax highlighting, and is also more easily optimized by many JS engines.
// badconst bad ='foo': 3'bar': 4'data-blah': 5;// goodconst good =foo: 3bar: 4'data-blah': 5;
-
3.7 Do not call
Object.prototype
methods directly, such ashasOwnProperty
,propertyIsEnumerable
, andisPrototypeOf
.Why? These methods may be shadowed by properties on the object in question - consider
{ hasOwnProperty: false }
- or, the object may be a null object (Object.create(null)
).// badconsole;// goodconsole;// bestconst has = ObjectprototypehasOwnProperty; // cache the lookup once, in module scope./* or */; // https://www.npmjs.com/package/has// ...console;
-
3.8 Prefer the object spread operator over
Object.assign
to shallow-copy objects. Use the object rest operator to get a new object with certain properties omitted.// very badconst original = a: 1 b: 2 ;const copy = Object; // this mutates `original` ಠ_ಠdelete copya; // so does this// badconst original = a: 1 b: 2 ;const copy = Object; // copy => { a: 1, b: 2, c: 3 }// goodconst original = a: 1 b: 2 ;const copy = ...original c: 3 ; // copy => { a: 1, b: 2, c: 3 }const a ...noA = copy; // noA => { b: 2, c: 3 }
Arrays
-
4.1 Use the literal syntax for array creation. eslint:
no-array-constructor
// badconst items = ;// goodconst items = ;
-
4.2 Use Array#push instead of direct assignment to add items to an array.
const someStack = ;// badsomeStacksomeStacklength = 'abracadabra';// goodsomeStack;
-
4.3 Use array spreads
...
to copy arrays.// badconst len = itemslength;const itemsCopy = ;let i;for i = 0; i < len; i += 1itemsCopyi = itemsi;// goodconst itemsCopy = ...items;
-
4.4 To convert an array-like object to an array, use spreads
...
instead ofArray.from
.const foo = document;// goodconst nodes = Array;// bestconst nodes = ...foo;
-
4.5 Use Array.from instead of spread
...
for mapping over iterables, because it avoids creating an intermediate array.// badconst baz = ...foo;// goodconst baz = Array;
-
4.6 Use return statements in array method callbacks. It’s ok to omit the return if the function body consists of a single statement returning an expression without side effects, following 8.2. eslint:
array-callback-return
// good1 2 3;// good1 2 3;// bad - no returned value means `acc` becomes undefined after the first iteration0 1 2 3 4 5;// good0 1 2 3 4 5;// badinbox;// goodinbox;
-
4.7 Use line breaks after open and before close array brackets if an array has multiple lines
// badconst arr =0 1 2 3 4 5;const objectInArray =id: 1id: 2;const numberInArray =1 2;// goodconst arr = 0 1 2 3 4 5;const objectInArray =id: 1id: 2;const numberInArray =12;
Destructuring
-
5.1 Use object destructuring when accessing and using multiple properties of an object. eslint:
prefer-destructuring
Why? Destructuring saves you from creating temporary references for those properties.
// bad{const firstName = userfirstName;const lastName = userlastName;return ` `;}// good{const firstName lastName = user;return ` `;}// best{return ` `;}
-
5.2 Use array destructuring. eslint:
prefer-destructuring
const arr = 1 2 3 4;// badconst first = arr0;const second = arr1;// goodconst first second = arr;
-
5.3 Use object destructuring for multiple return values, not array destructuring.
Why? You can add new properties over time or change the order of things without breaking call sites.
// bad{// then a miracle occursreturn left right top bottom;}// the caller needs to think about the order of return dataconst left __ top = ;// good{// then a miracle occursreturn left right top bottom ;}// the caller selects only the data they needconst left top = ;
Strings
-
6.1 Use single quotes
''
for strings. eslint:quotes
// badconst name = "Capt. Janeway";// bad - template literals should contain interpolation or newlinesconst name = `Capt. Janeway`;// goodconst name = 'Capt. Janeway';
-
6.2 Strings that cause the line to go over 100 characters should not be written across multiple lines using string concatenation.
Why? Broken strings are painful to work with and make code less searchable.
// badconst errorMessage = 'This is a super long error that was thrown because \of Batman. When you stop to think about how Batman had anything to do \with this, you would get nowhere \fast.';// badconst errorMessage = 'This is a super long error that was thrown because ' +'of Batman. When you stop to think about how Batman had anything to do ' +'with this, you would get nowhere fast.';// goodconst errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.';
-
6.3 When programmatically building up strings, use template strings instead of concatenation. eslint:
prefer-template
template-curly-spacing
Why? Template strings give you a readable, concise syntax with proper newlines and string interpolation features.
// bad{return 'How are you, ' + name + '?';}// bad{return 'How are you, ' name '?';}// bad{return `How are you, ?`;}// good{return `How are you, ?`;}
-
6.5 Do not unnecessarily escape characters in strings. eslint:
no-useless-escape
Why? Backslashes harm readability, thus they should only be present when necessary.
// badconst foo = '\'this\' \i\s \"quoted\"';// goodconst foo = '\'this\' is "quoted"';const foo = `my name is ''`;
Functions
-
7.1 Use named function expressions instead of function declarations. eslint:
func-style
Why? Function declarations are hoisted, which means that it’s easy - too easy - to reference the function before it is defined in the file. This harms readability and maintainability. If you find that a function’s definition is large or complex enough that it is interfering with understanding the rest of the file, then perhaps it’s time to extract it to its own module! Don’t forget to explicitly name the expression, regardless of whether or not the name is inferred from the containing variable (which is often the case in modern browsers or when using compilers such as Babel). This eliminates any assumptions made about the Error's call stack. (Discussion)
// bad{// ...}// badconst foo = {// ...};// good// lexical name distinguished from the variable-referenced invocation(s)const short = {// ...};
-
7.2 Wrap immediately invoked function expressions in parentheses. eslint:
wrap-iife
Why? An immediately invoked function expression is a single unit - wrapping both it, and its invocation parens, in parens, cleanly expresses this. Note that in a world with modules everywhere, you almost never need an IIFE.
// immediately-invoked function expression (IIFE){console;};
- 7.3 Never declare a function in a non-function block (
if
,while
, etc). Assign the function to a variable instead. Browsers will allow you to do it, but they all interpret it differently, which is bad news bears. eslint:no-loop-func
-
7.4 Note: ECMA-262 defines a
block
as a list of statements. A function declaration is not a statement.// badif currentUser{console;}// goodlet test;if currentUser{console;};
-
7.5 Never name a parameter
arguments
. This will take precedence over thearguments
object that is given to every function scope.// bad{// ...}// good{// ...}
-
7.6 Never use
arguments
, opt to use rest syntax...
instead. eslint:prefer-rest-params
Why?
...
is explicit about which arguments you want pulled. Plus, rest arguments are a real Array, and not merely Array-like likearguments
.// bad{const args = Arrayprototypeslice;return args;}// good{return args;}
-
7.7 Use default parameter syntax rather than mutating function arguments.
// really bad{// No! We shouldn’t mutate function arguments.// Double bad: if opts is falsy it'll be set to an object which may// be what you want but it can introduce subtle bugs.opts = opts || {};// ...}// still bad{if opts === void 0opts = {};// ...}// good{// ...}
-
7.8 Avoid side effects with default parameters.
Why? They are confusing to reason about.
var b = 1;// bad{console;}; // 1; // 2; // 3; // 3
-
7.9 Always put default parameters last.
// bad{// ...}// good{// ...}
-
7.10 Never use the Function constructor to create a new function. eslint:
no-new-func
Why? Creating a function in this way evaluates a string similarly to
eval()
, which opens vulnerabilities.// badvar add = 'a' 'b' 'return a + b';// still badvar subtract = Function'a' 'b' 'return a - b';
-
7.11 Spacing in a function signature. eslint:
space-before-function-paren
space-before-blocks
Why? Consistency is good, and you shouldn’t have to add or remove a space when adding or removing a name.
// badconst f = {};const g = {};const h = {};// goodconst x = {};const y = {};
-
7.12 Never mutate parameters. eslint:
no-param-reassign
Why? Manipulating objects passed in as parameters can cause unwanted variable side effects in the original caller.
// bad{objkey = 1;}// good{const key = ObjectprototypehasOwnProperty ? objkey : 1;}
-
7.13 Never reassign parameters. eslint:
no-param-reassign
Why? Reassigning parameters can lead to unexpected behavior, especially when accessing the
arguments
object. It can also cause optimization issues, especially in V8.// bad{a = 1;// ...}{if !a a = 1;// ...}// good{const b = a || 1;// ...}{// ...}
-
7.14 Prefer the use of the spread operator
...
to call variadic functions. eslint:prefer-spread
Why? It’s cleaner, you don’t need to supply a context, and you can not easily compose
new
withapply
.// badconst x = 1 2 3 4 5;consolelog;// goodconst x = 1 2 3 4 5;console;// badnew Functionprototypebind;// good...2016 8 5;
-
7.15 Functions with multiline signatures, or invocations, should be indented just like every other multiline list in this guide: with each item on a line by itself, with a trailing comma on the last item. eslint:
function-paren-newline
// bad{// ...}// good{// ...}// badconsole;// goodconsole;
Arrow Functions
-
8.1 When you must use an anonymous function (as when passing an inline callback), use arrow function notation. eslint:
prefer-arrow-callback
,arrow-spacing
Why? It creates a version of the function that executes in the context of
this
, which is usually what you want, and is a more concise syntax.Why not? If you have a fairly complicated function, you might move that logic out into its own named function expression.
// bad1 2 3;// good1 2 3;
-
8.2 If the function body consists of a single statement returning an expression without side effects, omit the braces and use the implicit return. Otherwise, keep the braces and use a
return
statement. eslint:arrow-parens
,arrow-body-style
Why? Syntactic sugar. It reads well when multiple functions are chained together.
// bad1 2 3;// good1 2 3;// good1 2 3;// good1 2 3;// No implicit return with side effects{const val = ;if val === true// Do something if callback returns true}let bool = false;// bad;// good;
-
8.3 In case the expression spans over multiple lines, wrap it in parentheses for better readability.
Why? It shows clearly where the function starts and ends.
// bad'get' 'post' 'put';// good'get' 'post' 'put';
-
8.4 If your function takes a single argument and doesn’t use braces, omit the parentheses. Otherwise, always include parentheses around arguments for clarity and consistency. Note: it is also acceptable to always use parentheses, in which case use the “always” option for eslint. eslint:
arrow-parens
Why? Less visual clutter.
// bad1 2 3;// good1 2 3;// good1 2 3;// bad1 2 3;// good1 2 3;
-
8.5 Avoid confusing arrow function syntax (
=>
) with comparison operators (<=
,>=
). eslint:no-confusing-arrow
// badconst itemHeight = itemheight > 256 ? itemlargeSize : itemsmallSize;// badconst itemHeight = itemheight > 256 ? itemlargeSize : itemsmallSize;// goodconst itemHeight = itemheight > 256 ? itemlargeSize : itemsmallSize;// goodconst itemHeight = {const height largeSize smallSize = item;return height > 256 ? largeSize : smallSize;};
-
8.6 Enforce the location of arrow function bodies with implicit returns. eslint:
implicit-arrow-linebreak
// badbar;bar;// goodbar;bar;bar
Classes & Constructors
-
9.1 Always use
class
. Avoid manipulatingprototype
directly.Why?
class
syntax is more concise and easier to reason about.// bad{thisqueue = ...contents;}Queueprototype {const value = thisqueue0;thisqueue;return value;};// good{thisqueue = ...contents;}{const value = thisqueue0;thisqueue;return value;}
-
9.2 Use
extends
for inheritance.Why? It is a built-in way to inherit prototype functionality without breaking
instanceof
.// badconst inherits = ;{Queue;};PeekableQueueprototype {return thisqueue0;};// good{return thisqueue0;}
-
9.3 Methods can return
this
to help with method chaining.// badJediprototype {thisjumping = true;return true;};Jediprototype {thisheight = height;};const luke = ;luke; // => trueluke; // => undefined// good{thisjumping = true;return this;}{thisheight = height;return this;}const luke = ;luke;
-
9.4 It’s okay to write a custom
toString()
method, just make sure it works successfully and causes no side effects.{thisname = optionsname || 'no name';}{return thisname;}{return `Jedi - `;}
-
9.5 Classes have a default constructor if one is not specified. An empty constructor function or one that just delegates to a parent class is unnecessary. eslint:
no-useless-constructor
// bad{}{return thisname;}// bad{super...args;}// good{super...args;thisname = 'Rey';}
-
9.6 Avoid duplicate class members. eslint:
no-dupe-class-members
Why? Duplicate class member declarations will silently prefer the last one - having duplicates is almost certainly a bug.
// bad{ return 1; }{ return 2; }// good{ return 1; }// good{ return 2; }
Modules
-
10.1 Always use modules (
import
/export
) over a non-standard module system. You can always transpile to your preferred module system.Why? Modules are the future, let’s start using the future now.
// badconst AirbnbStyleGuide = ;moduleexports = AirbnbStyleGuidees6;// ok;es6;// best;;
-
10.2 Do not use wildcard imports.
Why? This makes sure you have a single default export.
// bad;// good;
-
10.3 And do not export directly from an import.
Why? Although the one-liner is concise, having one clear way to import and one clear way to export makes things consistent.
// bad// filename es6.js;// good// filename es6.js;;
-
10.4 Only import from a path in one place. eslint:
no-duplicate-imports
Why? Having multiple lines that import from the same path can make code harder to maintain.
// bad;// … some other imports … //;// good;// good;
-
10.5 Do not export mutable bindings. eslint:
import/no-mutable-exports
Why? Mutation should be avoided in general, but in particular when exporting mutable bindings. While this technique may be needed for some special cases, in general, only constant references should be exported.
// badlet foo = 3;;// goodconst foo = 3;;
-
10.6 In modules with a single export, prefer default export over named export. eslint:
import/prefer-default-export
Why? To encourage more files that only ever export one thing, which is better for readability and maintainability.
// bad{}// good{}
-
10.7 Put all
import
s above non-import statements. eslint:import/first
Why? Since
import
s are hoisted, keeping them all at the top prevents surprising behavior.// bad;foo;;// good;;foo;
-
10.8 Multiline imports should be indented just like multiline array and object literals.
Why? The curly braces follow the same indentation rules as every other curly brace block in the style guide, as do the trailing commas.
// bad;// good;
-
10.9 Disallow Webpack loader syntax in module import statements. eslint:
import/no-webpack-loader-syntax
Why? Since using Webpack syntax in the imports couples the code to a module bundler. Prefer using the loader syntax in
webpack.config.js
.// bad;;// good;;
Iterators and Generators
-
11.1 Don’t use iterators. Prefer JavaScript’s higher-order functions instead of loops like
for-in
orfor-of
. eslint:no-iterator
no-restricted-syntax
Why? This enforces our immutable rule. Dealing with pure functions that return values is easier to reason about than side effects.
Use
map()
/every()
/filter()
/find()
/findIndex()
/reduce()
/some()
/ ... to iterate over arrays, andObject.keys()
/Object.values()
/Object.entries()
to produce arrays so you can iterate over objects.const numbers = 1 2 3 4 5;// badlet sum = 0;for let num of numberssum += num;sum === 15;// goodlet sum = 0;numbers;sum === 15;// best (use the functional force)const sum = numbers;sum === 15;// badconst increasedByOne = ;for let i = 0; i < numberslength; i++increasedByOne;// goodconst increasedByOne = ;numbers;// best (keeping it functional)const increasedByOne = numbers;
-
11.2 Don’t use generators for now.
Why? They don’t transpile well to ES5.
-
11.3 If you must use generators, or if you disregard our advice, make sure their function signature is spaced properly. eslint:
generator-star-spacing
Why?
function
and*
are part of the same conceptual keyword -*
is not a modifier forfunction
,function*
is a unique construct, different fromfunction
.// bad{// ...}// badconst bar = {// ...};// badconst baz = {// ...};// badconst quux = {// ...};// bad{// ...}// bad{// ...}// very bad{// ...}// very badconst wat ={// ...};// good{// ...}// goodconst foo = {// ...};
Properties
-
12.1 Use dot notation when accessing properties. eslint:
dot-notation
const luke =jedi: trueage: 28;// badconst isJedi = luke'jedi';// goodconst isJedi = lukejedi;
-
12.2 Use bracket notation
[]
when accessing properties with a variable.const luke =jedi: trueage: 28;{return lukeprop;}const isJedi = ;
-
12.3 Use exponentiation operator
**
when calculating exponentiations. eslint:no-restricted-properties
.// badconst binary = Math;// goodconst binary = 2 ** 10;
Variables
-
13.1 Always use
const
orlet
to declare variables. Not doing so will result in global variables. We want to avoid polluting the global namespace. Captain Planet warned us of that. eslint:no-undef
prefer-const
// badsuperPower = ;// goodconst superPower = ;
-
13.2 Use one
const
orlet
declaration per variable. eslint:one-var
Why? It’s easier to add new variable declarations this way, and you never have to worry about swapping out a
;
for a,
or introducing punctuation-only diffs. You can also step through each declaration with the debugger, instead of jumping through all of them at once.// badconst items =goSportsTeam = truedragonball = 'z';// bad// (compare to above, and try to spot the mistake)const items =goSportsTeam = true;dragonball = 'z';// goodconst items = ;const goSportsTeam = true;const dragonball = 'z';
-
13.3 Group all your
const
s and then group all yourlet
s.Why? This is helpful when later on you might need to assign a variable depending on one of the previous assigned variables.
// badlet i len dragonballitems =goSportsTeam = true;// badlet i;const items = ;let dragonball;const goSportsTeam = true;let len;// goodconst goSportsTeam = true;const items = ;let dragonball;let i;let length;
-
13.4 Assign variables where you need them, but place them in a reasonable place.
Why?
let
andconst
are block scoped and not function scoped.// bad - unnecessary function call{const name = ;if hasName === 'test'return false;if name === 'test'this;return false;return name;}// good{if hasName === 'test'return false;const name = ;if name === 'test'this;return false;return name;}
-
13.5 Don’t chain variable assignments. eslint:
no-multi-assign
Why? Chaining variable assignments creates implicit global variables.
// bad{// JavaScript interprets this as// let a = ( b = ( c = 1 ) );// The let keyword only applies to variable a; variables b and c become// global variables.let a = b = c = 1;};console; // throws ReferenceErrorconsole; // 1console; // 1// good{let a = 1;let b = a;let c = a;};console; // throws ReferenceErrorconsole; // throws ReferenceErrorconsole; // throws ReferenceError// the same applies for `const`
-
13.6 Avoid using unary increments and decrements (
++
,--
). eslintno-plusplus
Why? Per the eslint documentation, unary increment and decrement statements are subject to automatic semicolon insertion and can cause silent errors with incrementing or decrementing values within an application. It is also more expressive to mutate your values with statements like
num += 1
instead ofnum++
ornum ++
. Disallowing unary increment and decrement statements also prevents you from pre-incrementing/pre-decrementing values unintentionally which can also cause unexpected behavior in your programs.// badconst array = 1 2 3;let num = 1;num++;--num;let sum = 0;let truthyCount = 0;for let i = 0; i < arraylength; i++let value = arrayi;sum += value;if valuetruthyCount++;// goodconst array = 1 2 3;let num = 1;num += 1;num -= 1;const sum = array;const truthyCount = arraylength;
-
13.7 Avoid linebreaks before or after
=
in an assignment. If your assignment violatesmax-len
, surround the value in parens. eslintoperator-linebreak
.Why? Linebreaks surrounding
=
can obfuscate the value of an assignment.// badconst foo =;// badconst foo= 'superLongLongLongLongLongLongLongLongString';// goodconst foo =;// goodconst foo = 'superLongLongLongLongLongLongLongLongString';
-
13.8 Disallow unused variables. eslint:
no-unused-vars
Why? Variables that are declared and not used anywhere in the code are most likely an error due to incomplete refactoring. Such variables take up space in the code and can lead to confusion by readers.
// badvar some_unused_var = 42;// Write-only variables are not considered as used.var y = 10;y = 5;// A read for a modification of itself is not considered as used.var z = 0;z = z + 1;// Unused function arguments.{return x;}// good{return x + y;}var x = 1;var y = a + 2;;// 'type' is ignored even if unused because it has a rest property sibling.// This is a form of extracting an object that omits the specified keys.var type ...coords = data;// 'coords' is now the 'data' object without its 'type' property.
Hoisting
-
14.1
var
declarations get hoisted to the top of their closest enclosing function scope, their assignment does not.const
andlet
declarations are blessed with a new concept called Temporal Dead Zones (TDZ). It’s important to know why typeof is no longer safe.// we know this wouldn’t work (assuming there// is no notDefined global variable){console; // => throws a ReferenceError}// creating a variable declaration after you// reference the variable will work due to// variable hoisting. Note: the assignment// value of `true` is not hoisted.{console; // => undefinedvar declaredButNotAssigned = true;}// the interpreter is hoisting the variable// declaration to the top of the scope,// which means our example could be rewritten as:{let declaredButNotAssigned;console; // => undefineddeclaredButNotAssigned = true;}// using const and let{console; // => throws a ReferenceErrorconsole; // => throws a ReferenceErrorconst declaredButNotAssigned = true;}
-
14.2 Anonymous function expressions hoist their variable name, but not the function assignment.
{console; // => undefined; // => TypeError anonymous is not a functionvar {console;};}
-
14.3 Named function expressions hoist the variable name, not the function name or the function body.
{console; // => undefined; // => TypeError named is not a function; // => ReferenceError superPower is not definedvar {console;};}// the same is true when the function name// is the same as the variable name.{console; // => undefined; // => TypeError named is not a functionvar {console;};}
-
14.4 Function declarations hoist their name and the function body.
{; // => Flying{console;}} -
For more information refer to JavaScript Scoping & Hoisting by Ben Cherry.
Comparison Operators & Equality
-
15.2 Conditional statements such as the
if
statement evaluate their expression using coercion with theToBoolean
abstract method and always follow these simple rules:- Objects evaluate to true
- Undefined evaluates to false
- Null evaluates to false
- Booleans evaluate to the value of the boolean
- Numbers evaluate to false if +0, -0, or NaN, otherwise true
- Strings evaluate to false if an empty string
''
, otherwise true
if 0 &&// true// an array (even an empty one) is an object, objects will evaluate to true
-
15.3 Use shortcuts for booleans, but explicit comparisons for strings and numbers.
// badif isValid === true// ...// goodif isValid// ...// badif name// ...// goodif name !== ''// ...// badif collectionlength// ...// goodif collectionlength > 0// ...
- 15.4 For more information see Truth Equality and JavaScript by Angus Croll.
-
15.5 Use braces to create blocks in
case
anddefault
clauses that contain lexical declarations (e.g.let
,const
,function
, andclass
). eslint:no-case-declarations
Why? Lexical declarations are visible in the entire
switch
block but only get initialized when assigned, which only happens when itscase
is reached. This causes problems when multiplecase
clauses attempt to define the same thing.// bad// good
-
15.6 Ternaries should not be nested and generally be single line expressions. eslint:
no-nested-ternary
// badconst foo = maybe1 > maybe2? "bar": value1 > value2 ? "baz" : null;// split into 2 separated ternary expressionsconst maybeNull = value1 > value2 ? 'baz' : null;// betterconst foo = maybe1 > maybe2? 'bar': maybeNull;// bestconst foo = maybe1 > maybe2 ? 'bar' : maybeNull;
-
15.7 Avoid unneeded ternary statements. eslint:
no-unneeded-ternary
// badconst foo = a ? a : b;const bar = c ? true : false;const baz = c ? false : true;// goodconst foo = a || b;const bar = !!c;const baz = !c;
-
15.8 When mixing operators, enclose them in parentheses. The only exception is the standard arithmetic operators (
+
,-
,*
, &/
) since their precedence is broadly understood. eslint:no-mixed-operators
Why? This improves readability and clarifies the developer’s intention.
// badconst foo = a && b < 0 || c > 0 || d + 1 === 0;// badconst bar = a ** b - 5 % d;// bad// one may be confused into thinking (a || b) && cif a || b && creturn d;// goodconst foo = a && b < 0 || c > 0 || d + 1 === 0;// goodconst bar = a ** b - 5 % d;// goodif a || b && creturn d;// goodconst bar = a + b / c * d;
Blocks
-
16.1 Use braces with all multi-line blocks. eslint:
nonblock-statement-body-position
// badif testreturn false;// goodif test return false;// goodif testreturn false;// bad{ return false; }// good{return false;}
-
16.2 If you're using multi-line blocks with
if
andelse
, putelse
on the same line as yourif
block’s closing brace. eslint:brace-style
// badif test;;else;// goodif test;;else;
-
16.3 If an
if
block always executes areturn
statement, the subsequentelse
block is unnecessary. Areturn
in anelse if
block following anif
block that contains areturn
can be separated into multipleif
blocks. eslint:no-else-return
// bad{if xreturn x;elsereturn y;}// bad{if xreturn x;else if yreturn y;}// bad{if xreturn x;elseif yreturn y;}// good{if xreturn x;return y;}// good{if xreturn x;if yreturn y;}// good{if xif zreturn y;elsereturn z;}
Control Statements
-
17.1 In case your control statement (
if
,while
etc.) gets too long or exceeds the maximum line length, each (grouped) condition could be put into a new line. The logical operator should begin the line.Why? Requiring operators at the beginning of the line keeps the operators aligned and follows a pattern similar to method chaining. This also improves readability by making it easier to visually follow complex logic.
// badif foo === 123 || bar === 'abc' && &&;// badif foo === 123 &&bar === 'abc';// badif foo === 123&& bar === 'abc';// badiffoo === 123 &&bar === 'abc';// goodiffoo === 123&& bar === 'abc';// goodiffoo === 123 || bar === 'abc'&&&&;// goodif foo === 123 && bar === 'abc';
-
17.2 Don't use selection operators in place of control statements.
// bad!isRunning && ;// goodif !isRunning;
Comments
-
18.1 Use
/** ... */
for multi-line comments.// bad// make() returns a new element// based on the passed in tag name//// @param {String} tag// @return {Element} element{// ...return element;}// good/*** make() returns a new element* based on the passed-in tag name*/{// ...return element;}
-
18.2 Use
//
for single line comments. Place single line comments on a newline above the subject of the comment. Put an empty line before the comment unless it’s on the first line of a block.// badconst active = true; // is current tab// good// is current tabconst active = true;// bad{console;// set the default type to 'no type'const type = thistype || 'no type';return type;}// good{console;// set the default type to 'no type'const type = thistype || 'no type';return type;}// also good{// set the default type to 'no type'const type = thistype || 'no type';return type;}
-
18.3 Start all comments with a space to make it easier to read. eslint:
spaced-comment
// bad//is current tabconst active = true;// good// is current tabconst active = true;// bad/***make() returns a new element*based on the passed-in tag name*/{// ...return element;}// good/*** make() returns a new element* based on the passed-in tag name*/{// ...return element;}
- 18.4 Prefixing your comments with
FIXME
orTODO
helps other developers quickly understand if you're pointing out a problem that needs to be revisited, or if you're suggesting a solution to the problem that needs to be implemented. These are different than regular comments because they are actionable. The actions areFIXME: -- need to figure this out
orTODO: -- need to implement
.
-
18.5 Use
// FIXME:
to annotate problems.{super;// FIXME: shouldn’t use a global heretotal = 0;}
-
18.6 Use
// TODO:
to annotate solutions to problems.{super;// TODO: total should be configurable by an options paramthistotal = 0;}
Whitespace
-
19.1 Use soft tabs (space character) set to 2 spaces. eslint:
indent
// bad{∙∙∙∙let name;}// bad{∙let name;}// good{∙∙let name;}
-
19.2 Place 1 space before the leading brace. eslint:
space-before-blocks
// bad{console;}// good{console;}// baddog;// gooddog;
-
19.3 Place 1 space before the opening parenthesis in control statements (
if
,while
etc.). Place no space between the argument list and the function name in function calls and declarations. eslint:keyword-spacing
// badifisJedi;// goodif isJedi;// bad{console;}// good{console;}
-
19.4 Set off operators with spaces. eslint:
space-infix-ops
// badconst x=y+5;// goodconst x = y + 5;
-
19.5 End files with a single newline character. eslint:
eol-last
// bad;// ...;// bad;// ...;↵↵// good;// ...;↵
-
19.6 Use indentation when making long method chains (more than 2 method chains). Use a leading dot, which emphasizes that the line is a method call, not a new statement. eslint:
newline-per-chained-call
no-whitespace-before-property
// bad;// bad;// good;// badconst leds = stagedatadata;// goodconst leds = stagedatadata;// goodconst leds = stagedatadata;
-
19.7 Leave a blank line after blocks and before the next statement.
// badif fooreturn bar;return baz;// goodif fooreturn bar;return baz;// badconst obj ={}{};return obj;// goodconst obj ={}{};return obj;// badconst arr ={}{};return arr;// goodconst arr ={}{};return arr;
-
19.8 Do not pad your blocks with blank lines. eslint:
padded-blocks
// bad{console;}// badif bazconsole;elseconsole;// bad{thisbar = bar;}// good{console;}// goodif bazconsole;elseconsole;
-
19.9 Do not add spaces inside parentheses. eslint:
space-in-parens
// bad{return foo;}// good{return foo;}// badif fooconsole;// goodif fooconsole;
-
19.10 Do not add spaces inside brackets. eslint:
array-bracket-spacing
// badconst foo = 1 2 3 ;console;// goodconst foo = 1 2 3;console;
-
19.11 Add spaces inside curly braces. eslint:
object-curly-spacing
// badconst foo = clark: 'kent';// goodconst foo = clark: 'kent' ;
-
19.12 Avoid having lines of code that are longer than 100 characters (including whitespace). Note: per above, long strings are exempt from this rule, and should not be broken up. eslint:
max-len
Why? This ensures readability and maintainability.
// badconst foo = jsonData && jsonDatafoo && jsonDatafoobar && jsonDatafoobarbaz && jsonDatafoobarbazquux && jsonDatafoobarbazquuxxyzzy;// bad$;// goodconst foo = jsonData&& jsonDatafoo&& jsonDatafoobar&& jsonDatafoobarbaz&& jsonDatafoobarbazquux&& jsonDatafoobarbazquuxxyzzy;// good$;
-
19.13 Require consistent spacing inside an open block token and the next token on the same line. This rule also enforces consistent spacing inside a close block token and previous token on the same line. eslint:
block-spacing
// bad{return true;}if foo bar = 0;// good{ return true; }if foo bar = 0;
-
19.14 Avoid spaces before commas and require a space after commas. eslint:
comma-spacing
// badvar foo = 1bar = 2;var arr = 1 2;// goodvar foo = 1 bar = 2;var arr = 1 2;
-
19.15 Enforce spacing inside of computed properties. eslint:
computed-property-spacing
// badobjfooobj 'foo'var x = b : aobjfoo bar// goodobjfooobj'foo'var x = b: aobjfoobar
-
19.16 Enforce spacing between functions and their invocations. eslint:
func-call-spacing
// bad;func;// good;
-
19.17 Enforce spacing between keys and values in object literal properties. eslint:
key-spacing
// badvar obj = "foo" : 42 ;var obj2 = "foo":42 ;// goodvar obj = "foo": 42 ;
- 19.18 Avoid trailing spaces at the end of lines. eslint:
no-trailing-spaces
-
19.19 Avoid multiple empty lines and only allow one newline at the end of files. eslint:
no-multiple-empty-lines
// badvar x = 1;var y = 2;// goodvar x = 1;var y = 2;
Commas
-
20.1 Leading commas: Nope. eslint:
comma-style
// badconst story =onceuponaTime;// goodconst story =onceuponaTime;// badconst hero =firstName: 'Ada'lastName: 'Lovelace'birthYear: 1815superPower: 'computers';// goodconst hero =firstName: 'Ada'lastName: 'Lovelace'birthYear: 1815superPower: 'computers';
Semicolons
-
Why? When JavaScript encounters a line break without a semicolon, it uses a set of rules called Automatic Semicolon Insertion to determine whether or not it should regard that line break as the end of a statement, and (as the name implies) place a semicolon into your code before the line break if it thinks so. ASI contains a few eccentric behaviors, though, and your code will break if JavaScript misinterprets your line break. These rules will become more complicated as new features become a part of JavaScript. Explicitly terminating your statements and configuring your linter to catch missing semicolons will help prevent you from encountering issues.
// bad - raises exceptionconst luke = {}const leia = {}luke leia// bad - raises exceptionconst reaction = "No! That's impossible!"{// handle `leia`, `lando`, `chewie`, `r2`, `c3p0`// ...}// bad - returns `undefined` instead of the value on the next line - always happens when `return` is on a line by itself because of ASI!{return'search your feelings, you know it to be foo'}// goodconst luke = {};const leia = {};luke leia;// goodconst reaction = "No! That's impossible!";{// handle `leia`, `lando`, `chewie`, `r2`, `c3p0`// ...};// good{return 'search your feelings, you know it to be foo';}
Type Casting & Coercion
- 22.1 Perform type coercion at the beginning of the statement.
-
22.2 Strings: eslint:
no-new-wrappers
// => this.reviewScore = 9;// badconst totalScore = thisreviewScore; // typeof totalScore is "object" not "string"// badconst totalScore = thisreviewScore + ''; // invokes this.reviewScore.valueOf()// badconst totalScore = thisreviewScore; // isn’t guaranteed to return a string// goodconst totalScore = StringthisreviewScore;
-
22.3 Numbers: Use
Number
for type casting andparseInt
always with a radix for parsing strings. eslint:radix
no-new-wrappers
const inputValue = '4';// badconst val = inputValue;// badconst val = +inputValue;// badconst val = inputValue >> 0;// badconst val = ;// goodconst val = NumberinputValue;// goodconst val = ;
-
22.4 If for whatever reason you are doing something wild and
parseInt
is your bottleneck and need to use Bitshift for performance reasons, leave a comment explaining why and what you're doing.// good/*** parseInt was the reason my code was slow.* Bitshifting the String to coerce it to a* Number made it a lot faster.*/const val = inputValue >> 0;
-
22.5 Note: Be careful when using bitshift operations. Numbers are represented as 64-bit values, but bitshift operations always return a 32-bit integer (source). Bitshift can lead to unexpected behavior for integer values larger than 32 bits. Discussion. Largest signed 32-bit Int is 2,147,483,647:
2147483647 >> 0; // => 21474836472147483648 >> 0; // => -21474836482147483649 >> 0; // => -2147483647
-
22.6 Booleans: eslint:
no-new-wrappers
const age = 0;// badconst hasAge = age;// goodconst hasAge = Booleanage;// bestconst hasAge = !!age;
Naming Conventions
-
23.1 Avoid single letter names. Be descriptive with your naming. eslint:
id-length
// bad{// ...}// good{// ...}
-
23.2 Use camelCase when naming objects, functions, and instances. eslint:
camelcase
// badconst OBJEcttsssss = {};const this_is_my_object = {};{}// goodconst thisIsMyObject = {};{}
-
23.3 Use PascalCase only when naming constructors or classes. eslint:
new-cap
// bad{thisname = optionsname;}const bad =name: 'nope';// good{thisname = optionsname;}const good =name: 'yup';
-
23.4 Do not use trailing or leading underscores. eslint:
no-underscore-dangle
Why? JavaScript does not have the concept of privacy in terms of properties or methods. Although a leading underscore is a common convention to mean “private”, in fact, these properties are fully public, and as such, are part of your public API contract. This convention might lead developers to wrongly think that a change won’t count as breaking, or that tests aren’t needed. tl;dr: if you want something to be “private”, it must not be observably present.
// badthis__firstName__ = 'Panda';thisfirstName_ = 'Panda';this_firstName = 'Panda';// goodthisfirstName = 'Panda';// good, in environments where WeakMaps are available// see https://kangax.github.io/compat-table/es6/#test-WeakMapconst firstNames = ;firstNames;
-
23.5 Don’t save references to
this
. Use arrow functions or Function#bind.// bad{const self = this;return {console;};}// bad{const that = this;return {console;};}// good{return {console;};}
-
23.6 A base filename should exactly match the name of its default export.
// file 1 contents// ...;// file 2 contents{ return 42; }// file 3 contents{}// in some other file// bad; // PascalCase import/export, camelCase filename; // PascalCase import/filename, camelCase export; // PascalCase import/filename, camelCase export// bad; // PascalCase import/export, snake_case filename; // snake_case import/filename, camelCase export; // snake_case import, camelCase export; // requiring the index file explicitly; // requiring the index file explicitly// good; // PascalCase export/import/filename; // camelCase export/import/filename; // camelCase export/import/directory name/implicit "index"// ^ supports both insideDirectory.js and insideDirectory/index.js
-
23.7 Use camelCase when you export-default a function. Your filename should be identical to your function’s name.
{// ...};
-
23.8 Use PascalCase when you export a constructor / class / singleton / function library / bare object.
const AirbnbStyleGuide =es6:;;
-
23.9 Acronyms and initialisms should always be all capitalized, or all lowercased.
Why? Names are for readability, not to appease a computer algorithm.
// bad;// badconst HttpRequests =// ...;// good;// goodconst HTTPRequests =// ...;// also goodconst httpRequests =// ...;// best;// bestconst requests =// ...;
-
23.10 You may optionally uppercase a constant only if it (1) is exported, (2) is a
const
(it can not be reassigned), and (3) the programmer can trust it (and its nested properties) to never change.Why? This is an additional tool to assist in situations where the programmer would be unsure if a variable might ever change. UPPERCASE_VARIABLES are letting the programmer know that they can trust the variable (and its properties) not to change.
- What about all
const
variables? - This is unnecessary, so uppercasing should not be used for constants within a file. It should be used for exported constants however. - What about exported objects? - Uppercase at the top level of export (e.g.
EXPORTED_OBJECT.key
) and maintain that all nested properties do not change.
// badconst PRIVATE_VARIABLE = 'should not be unnecessarily uppercased within a file';// badconst THING_TO_BE_CHANGED = 'should obviously not be uppercased';// badlet REASSIGNABLE_VARIABLE = 'do not use let with uppercase variables';// ---// allowed but does not supply semantic valueconst apiKey = 'SOMEKEY';// better in most casesconst API_KEY = 'SOMEKEY';// ---// bad - unnecessarily uppercases key while adding no semantic valueconst MAPPING =KEY: 'value';// goodconst MAPPING =key: 'value'; - What about all
Accessors
- 24.1 Accessor functions for properties are not required.
-
24.2 Do not use JavaScript getters/setters as they cause unexpected side effects and are harder to test, maintain, and reason about. Instead, if you do make accessor functions, use
getVal()
andsetVal('hello')
.// bad{// ...}{// ...}// good{// ...}{// ...}
-
24.3 If the property/method is a
boolean
, useisVal()
orhasVal()
.// badif !dragonreturn false;// goodif !dragonreturn false;
-
24.4 It’s okay to create
get()
andset()
functions, but be consistent.{const lightsaber = optionslightsaber || 'blue';this;}{thiskey = val;}{return thiskey;}
Events
-
25.1 When attaching data payloads to events (whether DOM events or something more proprietary like Backbone events), pass an object literal (also known as a "hash") instead of a raw value. This allows a subsequent contributor to add more data to the event payload without finding and updating every handler for the event. For example, instead of:
// bad;// ...;prefer:
// good;// ...;
jQuery
-
26.1 Prefix jQuery object variables with a
$
.// badconst sidebar = ;// goodconst $sidebar = ;// goodconst $sidebarBtn = ;
-
26.2 Cache jQuery lookups.
// bad{;// ...;}// good{const $sidebar = ;$sidebar;// ...$sidebar;}
-
26.4 Use
find
with scoped jQuery object queries.// bad;// bad;// good;// good;// good$sidebar;
ECMAScript 5 Compatibility
- 27.1 Refer to Kangax’s ES5 compatibility table.
ECMAScript 6+ (ES 2015+) Styles
- 28.1 This is a collection of links to the various ES6+ features.
- Arrow Functions
- Classes
- Object Shorthand
- Object Concise
- Object Computed Properties
- Template Strings
- Destructuring
- Default Parameters
- Rest
- Array Spreads
- Let and Const
- Exponentiation Operator
- Iterators and Generators
- Modules
-
28.2 Do not use TC39 proposals that have not reached stage 3.
Why? They are not finalized, and they are subject to change or to be withdrawn entirely. We want to use JavaScript, and proposals are not JavaScript yet.
Standard Library
The Standard Library contains utilities that are functionally broken but remain for legacy reasons.
-
29.1 Use
Number.isNaN
instead of globalisNaN
. eslint:no-restricted-globals
Why? The global
isNaN
coerces non-numbers to numbers, returning true for anything that coerces to NaN. If this behavior is desired, make it explicit.// bad; // false; // true// goodNumber; // falseNumber; // true
-
29.2 Use
Number.isFinite
instead of globalisFinite
. eslint:no-restricted-globals
Why? The global
isFinite
coerces non-numbers to numbers, returning true for anything that coerces to a finite number. If this behavior is desired, make it explicit.// bad; // true// goodNumber; // falseNumber; // true
Testing
-
30.1 Yup.
{return true;}
- 30.2 No, but seriously:
- Whichever testing framework you use, you should be writing tests!
- Strive to write many small pure functions, and minimize where mutations occur.
- Be cautious about stubs and mocks - they can make your tests more brittle.
- We primarily use
mocha
andjest
at Airbnb.tape
is also used occasionally for small, separate modules. - 100% test coverage is a good goal to strive for, even if it’s not always practical to reach it.
- Whenever you fix a bug, write a regression test. A bug fixed without a regression test is almost certainly going to break again in the future.
Performance
- On Layout & Web Performance
- String vs Array Concat
- Try/Catch Cost In a Loop
- Bang Function
- jQuery Find vs Context, Selector
- innerHTML vs textContent for script text
- Long String Concatenation
- Are Javascript functions like
map()
,reduce()
, andfilter()
optimized for traversing arrays? - Loading...
Improving this config
Consider adding test cases if you're making complicated rules changes, like anything involving regexes. Perhaps in a distant future, we could use literate programming to structure our README as test cases for our .eslintrc?
You can run tests with npm test
.
You can make sure this module lints with itself using npm run lint
.
License
(The MIT License)
Copyright (c) 2018 Suhendra Ahmad
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Amendments
We encourage you to fork this guide and change the rules to fit your team’s style guide. Below, you may list some amendments to the style guide. This allows you to periodically update your style guide without having to deal with merge conflicts.