Installations
npm install @teamteanpm2024/quasi-occaecati-architecto
Developer Guide
Typescript
No
Module System
CommonJS
Node Version
20.12.2
NPM Version
10.5.0
Score
50.8
Supply Chain
93.5
Quality
80.3
Maintenance
100
Vulnerability
100
License
Releases
Unable to fetch releases
validate.email 🚀
Verify real, reachable, and deliverable emails with instant MX records, SMTP checks, and disposable email detection.
Download Statistics
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
Package Meta Information
Latest Version
1.1.5
Package Id
@teamteanpm2024/quasi-occaecati-architecto@1.1.5
Unpacked Size
142.12 kB
Size
38.02 kB
File Count
5
NPM Version
10.5.0
Node Version
20.12.2
Published on
Apr 29, 2024
Total Downloads
Cumulative downloads
Total Downloads
NaN
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
37
Airbnb JavaScript Style Guide() {
A mostly reasonable approach to JavaScript
Note: this guide assumes you are using Babel, and requires that you use babel-preset-airbnb or the equivalent. It also assumes you are installing shims/polyfills in your app, with airbnb-browser-shims or the equivalent.
This guide is available in other languages too. See Translation
Other Style Guides
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
bigint
1const foo = 1; 2let bar = foo; 3 4bar = 9; 5 6console.log(foo, bar); // => 1, 9
- Symbols and BigInts 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
1const foo = [1, 2]; 2const bar = foo; 3 4bar[0] = 9; 5 6console.log(foo[0], bar[0]); // => 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.
1// bad 2var a = 1; 3var b = 2; 4 5// good 6const a = 1; 7const 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
.1// bad 2var count = 1; 3if (true) { 4 count += 1; 5} 6 7// good, use the let. 8let count = 1; 9if (true) { 10 count += 1; 11}
-
2.3 Note that both
let
andconst
are block-scoped, whereasvar
is function-scoped.1// const and let only exist in the blocks they are defined in. 2{ 3 let a = 1; 4 const b = 1; 5 var c = 1; 6} 7console.log(a); // ReferenceError 8console.log(b); // ReferenceError 9console.log(c); // Prints 1
In the above code, you can see that referencing
a
andb
will produce a ReferenceError, whilec
contains the number. This is becausea
andb
are block scoped, whilec
is scoped to the containing function.
Objects
-
3.1 Use the literal syntax for object creation. eslint:
no-new-object
1// bad 2const item = new Object(); 3 4// good 5const 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.
1 2function getKey(k) { 3 return `a key named ${k}`; 4} 5 6// bad 7const obj = { 8 id: 5, 9 name: 'San Francisco', 10}; 11obj[getKey('enabled')] = true; 12 13// good 14const obj = { 15 id: 5, 16 name: 'San Francisco', 17 [getKey('enabled')]: true, 18};
-
3.3 Use object method shorthand. eslint:
object-shorthand
1// bad 2const atom = { 3 value: 1, 4 5 addValue: function (value) { 6 return atom.value + value; 7 }, 8}; 9 10// good 11const atom = { 12 value: 1, 13 14 addValue(value) { 15 return atom.value + value; 16 }, 17};
-
3.4 Use property value shorthand. eslint:
object-shorthand
Why? It is shorter and descriptive.
1const lukeSkywalker = 'Luke Skywalker'; 2 3// bad 4const obj = { 5 lukeSkywalker: lukeSkywalker, 6}; 7 8// good 9const obj = { 10 lukeSkywalker, 11};
-
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.
1const anakinSkywalker = 'Anakin Skywalker'; 2const lukeSkywalker = 'Luke Skywalker'; 3 4// bad 5const obj = { 6 episodeOne: 1, 7 twoJediWalkIntoACantina: 2, 8 lukeSkywalker, 9 episodeThree: 3, 10 mayTheFourth: 4, 11 anakinSkywalker, 12}; 13 14// good 15const obj = { 16 lukeSkywalker, 17 anakinSkywalker, 18 episodeOne: 1, 19 twoJediWalkIntoACantina: 2, 20 episodeThree: 3, 21 mayTheFourth: 4, 22};
-
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.
1// bad 2const bad = { 3 'foo': 3, 4 'bar': 4, 5 'data-blah': 5, 6}; 7 8// good 9const good = { 10 foo: 3, 11 bar: 4, 12 'data-blah': 5, 13};
-
3.7 Do not call
Object.prototype
methods directly, such ashasOwnProperty
,propertyIsEnumerable
, andisPrototypeOf
. eslint:no-prototype-builtins
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)
). In modern browsers that support ES2022, or with a polyfill such as https://npmjs.com/object.hasown,Object.hasOwn
can also be used as an alternative toObject.prototype.hasOwnProperty.call
.1// bad 2console.log(object.hasOwnProperty(key)); 3 4// good 5console.log(Object.prototype.hasOwnProperty.call(object, key)); 6 7// better 8const has = Object.prototype.hasOwnProperty; // cache the lookup once, in module scope. 9console.log(has.call(object, key)); 10 11// best 12console.log(Object.hasOwn(object, key)); // only supported in browsers that support ES2022 13 14/* or */ 15import has from 'has'; // https://www.npmjs.com/package/has 16console.log(has(object, key)); 17/* or */ 18console.log(Object.hasOwn(object, key)); // https://www.npmjs.com/package/object.hasown
-
3.8 Prefer the object spread syntax over
Object.assign
to shallow-copy objects. Use the object rest parameter syntax to get a new object with certain properties omitted. eslint:prefer-object-spread
1// very bad 2const original = { a: 1, b: 2 }; 3const copy = Object.assign(original, { c: 3 }); // this mutates `original` ಠ_ಠ4delete copy.a; // so does this 5 6// bad 7const original = { a: 1, b: 2 }; 8const copy = Object.assign({}, original, { c: 3 }); // copy => { a: 1, b: 2, c: 3 } 9 10// good 11const original = { a: 1, b: 2 }; 12const copy = { ...original, c: 3 }; // copy => { a: 1, b: 2, c: 3 } 13 14const { a, ...noA } = copy; // noA => { b: 2, c: 3 }
Arrays
-
4.1 Use the literal syntax for array creation. eslint:
no-array-constructor
1// bad 2const items = new Array(); 3 4// good 5const items = [];
-
4.2 Use Array#push instead of direct assignment to add items to an array.
1const someStack = []; 2 3// bad 4someStack[someStack.length] = 'abracadabra'; 5 6// good 7someStack.push('abracadabra');
-
4.3 Use array spreads
...
to copy arrays.1// bad 2const len = items.length; 3const itemsCopy = []; 4let i; 5 6for (i = 0; i < len; i += 1) { 7 itemsCopy[i] = items[i]; 8} 9 10// good 11const itemsCopy = [...items];
-
4.4 To convert an iterable object to an array, use spreads
...
instead ofArray.from
1const foo = document.querySelectorAll('.foo'); 2 3// good 4const nodes = Array.from(foo); 5 6// best 7const nodes = [...foo];
-
4.5 Use
Array.from
for converting an array-like object to an array.1const arrLike = { 0: 'foo', 1: 'bar', 2: 'baz', length: 3 }; 2 3// bad 4const arr = Array.prototype.slice.call(arrLike); 5 6// good 7const arr = Array.from(arrLike);
-
4.6 Use
Array.from
instead of spread...
for mapping over iterables, because it avoids creating an intermediate array.1// bad 2const baz = [...foo].map(bar); 3 4// good 5const baz = Array.from(foo, bar);
-
4.7 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
1// good 2[1, 2, 3].map((x) => { 3 const y = x + 1; 4 return x * y; 5}); 6 7// good 8[1, 2, 3].map((x) => x + 1); 9 10// bad - no returned value means `acc` becomes undefined after the first iteration 11[[0, 1], [2, 3], [4, 5]].reduce((acc, item, index) => { 12 const flatten = acc.concat(item); 13}); 14 15// good 16[[0, 1], [2, 3], [4, 5]].reduce((acc, item, index) => { 17 const flatten = acc.concat(item); 18 return flatten; 19}); 20 21// bad 22inbox.filter((msg) => { 23 const { subject, author } = msg; 24 if (subject === 'Mockingbird') { 25 return author === 'Harper Lee'; 26 } else { 27 return false; 28 } 29}); 30 31// good 32inbox.filter((msg) => { 33 const { subject, author } = msg; 34 if (subject === 'Mockingbird') { 35 return author === 'Harper Lee'; 36 } 37 38 return false; 39});
-
4.8 Use line breaks after opening array brackets and before closing array brackets, if an array has multiple lines
1// bad 2const arr = [ 3 [0, 1], [2, 3], [4, 5], 4]; 5 6const objectInArray = [{ 7 id: 1, 8}, { 9 id: 2, 10}]; 11 12const numberInArray = [ 13 1, 2, 14]; 15 16// good 17const arr = [[0, 1], [2, 3], [4, 5]]; 18 19const objectInArray = [ 20 { 21 id: 1, 22 }, 23 { 24 id: 2, 25 }, 26]; 27 28const numberInArray = [ 29 1, 30 2, 31];
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, and from repetitive access of the object. Repeating object access creates more repetitive code, requires more reading, and creates more opportunities for mistakes. Destructuring objects also provides a single site of definition of the object structure that is used in the block, rather than requiring reading the entire block to determine what is used.
1// bad 2function getFullName(user) { 3 const firstName = user.firstName; 4 const lastName = user.lastName; 5 6 return `${firstName} ${lastName}`; 7} 8 9// good 10function getFullName(user) { 11 const { firstName, lastName } = user; 12 return `${firstName} ${lastName}`; 13} 14 15// best 16function getFullName({ firstName, lastName }) { 17 return `${firstName} ${lastName}`; 18}
-
5.2 Use array destructuring. eslint:
prefer-destructuring
1const arr = [1, 2, 3, 4]; 2 3// bad 4const first = arr[0]; 5const second = arr[1]; 6 7// good 8const [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.
1// bad 2function processInput(input) { 3 // then a miracle occurs 4 return [left, right, top, bottom]; 5} 6 7// the caller needs to think about the order of return data 8const [left, __, top] = processInput(input); 9 10// good 11function processInput(input) { 12 // then a miracle occurs 13 return { left, right, top, bottom }; 14} 15 16// the caller selects only the data they need 17const { left, top } = processInput(input);
Strings
-
6.1 Use single quotes
''
for strings. eslint:quotes
1// bad 2const name = "Capt. Janeway"; 3 4// bad - template literals should contain interpolation or newlines 5const name = `Capt. Janeway`; 6 7// good 8const 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.
1// bad 2const errorMessage = 'This is a super long error that was thrown because \ 3of Batman. When you stop to think about how Batman had anything to do \ 4with this, you would get nowhere \ 5fast.'; 6 7// bad 8const errorMessage = 'This is a super long error that was thrown because ' + 9 'of Batman. When you stop to think about how Batman had anything to do ' + 10 'with this, you would get nowhere fast.'; 11 12// good 13const 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.
1// bad 2function sayHi(name) { 3 return 'How are you, ' + name + '?'; 4} 5 6// bad 7function sayHi(name) { 8 return ['How are you, ', name, '?'].join(); 9} 10 11// bad 12function sayHi(name) { 13 return `How are you, ${ name }?`; 14} 15 16// good 17function sayHi(name) { 18 return `How are you, ${name}?`; 19}
-
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.
1// bad 2const foo = '\'this\' \i\s \"quoted\"'; 3 4// good 5const foo = '\'this\' is "quoted"'; 6const foo = `my name is '${name}'`;
Functions
-
7.1 Use named function expressions instead of function declarations. eslint:
func-style
,func-names
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)
1// bad 2function foo() { 3 // ... 4} 5 6// bad 7const foo = function () { 8 // ... 9}; 10 11// good 12// lexical name distinguished from the variable-referenced invocation(s) 13const short = function longUniqueMoreDescriptiveLexicalFoo() { 14 // ... 15};
-
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.
1// immediately-invoked function expression (IIFE) 2(function () { 3 console.log('Welcome to the Internet. Please follow me.'); 4}());
- 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.1// bad 2if (currentUser) { 3 function test() { 4 console.log('Nope.'); 5 } 6} 7 8// good 9let test; 10if (currentUser) { 11 test = () => { 12 console.log('Yup.'); 13 }; 14}
-
7.5 Never name a parameter
arguments
. This will take precedence over thearguments
object that is given to every function scope.1// bad 2function foo(name, options, arguments) { 3 // ... 4} 5 6// good 7function foo(name, options, args) { 8 // ... 9}
-
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
.1// bad 2function concatenateAll() { 3 const args = Array.prototype.slice.call(arguments); 4 return args.join(''); 5} 6 7// good 8function concatenateAll(...args) { 9 return args.join(''); 10}
-
7.7 Use default parameter syntax rather than mutating function arguments.
1// really bad 2function handleThings(opts) { 3 // No! We shouldn’t mutate function arguments. 4 // Double bad: if opts is falsy it'll be set to an object which may 5 // be what you want but it can introduce subtle bugs. 6 opts = opts || {}; 7 // ... 8} 9 10// still bad 11function handleThings(opts) { 12 if (opts === void 0) { 13 opts = {}; 14 } 15 // ... 16} 17 18// good 19function handleThings(opts = {}) { 20 // ... 21}
-
7.8 Avoid side effects with default parameters.
Why? They are confusing to reason about.
1let b = 1; 2// bad 3function count(a = b++) { 4 console.log(a); 5} 6count(); // 1 7count(); // 2 8count(3); // 3 9count(); // 3
-
7.9 Always put default parameters last. eslint:
default-param-last
1// bad 2function handleThings(opts = {}, name) { 3 // ... 4} 5 6// good 7function handleThings(name, opts = {}) { 8 // ... 9}
-
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.1// bad 2const add = new Function('a', 'b', 'return a + b'); 3 4// still bad 5const 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.
1// bad 2const f = function(){}; 3const g = function (){}; 4const h = function() {}; 5 6// good 7const x = function () {}; 8const y = function a() {};
-
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.
1// bad 2function f1(obj) { 3 obj.key = 1; 4} 5 6// good 7function f2(obj) { 8 const key = Object.prototype.hasOwnProperty.call(obj, 'key') ? obj.key : 1; 9}
-
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.1// bad 2function f1(a) { 3 a = 1; 4 // ... 5} 6 7function f2(a) { 8 if (!a) { a = 1; } 9 // ... 10} 11 12// good 13function f3(a) { 14 const b = a || 1; 15 // ... 16} 17 18function f4(a = 1) { 19 // ... 20}
-
7.14 Prefer the use of the spread syntax
...
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
.1// bad 2const x = [1, 2, 3, 4, 5]; 3console.log.apply(console, x); 4 5// good 6const x = [1, 2, 3, 4, 5]; 7console.log(...x); 8 9// bad 10new (Function.prototype.bind.apply(Date, [null, 2016, 8, 5])); 11 12// good 13new Date(...[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
1// bad 2function foo(bar, 3 baz, 4 quux) { 5 // ... 6} 7 8// good 9function foo( 10 bar, 11 baz, 12 quux, 13) { 14 // ... 15} 16 17// bad 18console.log(foo, 19 bar, 20 baz); 21 22// good 23console.log( 24 foo, 25 bar, 26 baz, 27);
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.
1// bad 2[1, 2, 3].map(function (x) { 3 const y = x + 1; 4 return x * y; 5}); 6 7// good 8[1, 2, 3].map((x) => { 9 const y = x + 1; 10 return x * y; 11});
-
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.
1// bad 2[1, 2, 3].map((number) => { 3 const nextNumber = number + 1; 4 `A string containing the ${nextNumber}.`; 5}); 6 7// good 8[1, 2, 3].map((number) => `A string containing the ${number + 1}.`); 9 10// good 11[1, 2, 3].map((number) => { 12 const nextNumber = number + 1; 13 return `A string containing the ${nextNumber}.`; 14}); 15 16// good 17[1, 2, 3].map((number, index) => ({ 18 [index]: number, 19})); 20 21// No implicit return with side effects 22function foo(callback) { 23 const val = callback(); 24 if (val === true) { 25 // Do something if callback returns true 26 } 27} 28 29let bool = false; 30 31// bad 32foo(() => bool = true); 33 34// good 35foo(() => { 36 bool = true; 37});
-
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.
1// bad 2['get', 'post', 'put'].map((httpMethod) => Object.prototype.hasOwnProperty.call( 3 httpMagicObjectWithAVeryLongName, 4 httpMethod, 5 ) 6); 7 8// good 9['get', 'post', 'put'].map((httpMethod) => ( 10 Object.prototype.hasOwnProperty.call( 11 httpMagicObjectWithAVeryLongName, 12 httpMethod, 13 ) 14));
-
8.4 Always include parentheses around arguments for clarity and consistency. eslint:
arrow-parens
Why? Minimizes diff churn when adding or removing arguments.
1// bad 2[1, 2, 3].map(x => x * x); 3 4// good 5[1, 2, 3].map((x) => x * x); 6 7// bad 8[1, 2, 3].map(number => ( 9 `A long string with the ${number}. It’s so long that we don’t want it to take up space on the .map line!` 10)); 11 12// good 13[1, 2, 3].map((number) => ( 14 `A long string with the ${number}. It’s so long that we don’t want it to take up space on the .map line!` 15)); 16 17// bad 18[1, 2, 3].map(x => { 19 const y = x + 1; 20 return x * y; 21}); 22 23// good 24[1, 2, 3].map((x) => { 25 const y = x + 1; 26 return x * y; 27});
-
8.5 Avoid confusing arrow function syntax (
=>
) with comparison operators (<=
,>=
). eslint:no-confusing-arrow
1// bad 2const itemHeight = (item) => item.height <= 256 ? item.largeSize : item.smallSize; 3 4// bad 5const itemHeight = (item) => item.height >= 256 ? item.largeSize : item.smallSize; 6 7// good 8const itemHeight = (item) => (item.height <= 256 ? item.largeSize : item.smallSize); 9 10// good 11const itemHeight = (item) => { 12 const { height, largeSize, smallSize } = item; 13 return height <= 256 ? largeSize : smallSize; 14};
-
8.6 Enforce the location of arrow function bodies with implicit returns. eslint:
implicit-arrow-linebreak
1// bad 2(foo) => 3 bar; 4 5(foo) => 6 (bar); 7 8// good 9(foo) => bar; 10(foo) => (bar); 11(foo) => ( 12 bar 13)
Classes & Constructors
-
9.1 Always use
class
. Avoid manipulatingprototype
directly.Why?
class
syntax is more concise and easier to reason about.1// bad 2function Queue(contents = []) { 3 this.queue = [...contents]; 4} 5Queue.prototype.pop = function () { 6 const value = this.queue[0]; 7 this.queue.splice(0, 1); 8 return value; 9}; 10 11// good 12class Queue { 13 constructor(contents = []) { 14 this.queue = [...contents]; 15 } 16 pop() { 17 const value = this.queue[0]; 18 this.queue.splice(0, 1); 19 return value; 20 } 21}
-
9.2 Use
extends
for inheritance.Why? It is a built-in way to inherit prototype functionality without breaking
instanceof
.1// bad 2const inherits = require('inherits'); 3function PeekableQueue(contents) { 4 Queue.apply(this, contents); 5} 6inherits(PeekableQueue, Queue); 7PeekableQueue.prototype.peek = function () { 8 return this.queue[0]; 9}; 10 11// good 12class PeekableQueue extends Queue { 13 peek() { 14 return this.queue[0]; 15 } 16}
-
9.3 Methods can return
this
to help with method chaining.1// bad 2Jedi.prototype.jump = function () { 3 this.jumping = true; 4 return true; 5}; 6 7Jedi.prototype.setHeight = function (height) { 8 this.height = height; 9}; 10 11const luke = new Jedi(); 12luke.jump(); // => true 13luke.setHeight(20); // => undefined 14 15// good 16class Jedi { 17 jump() { 18 this.jumping = true; 19 return this; 20 } 21 22 setHeight(height) { 23 this.height = height; 24 return this; 25 } 26} 27 28const luke = new Jedi(); 29 30luke.jump() 31 .setHeight(20);
-
9.4 It’s okay to write a custom
toString()
method, just make sure it works successfully and causes no side effects.1class Jedi { 2 constructor(options = {}) { 3 this.name = options.name || 'no name'; 4 } 5 6 getName() { 7 return this.name; 8 } 9 10 toString() { 11 return `Jedi - ${this.getName()}`; 12 } 13}
-
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
1// bad 2class Jedi { 3 constructor() {} 4 5 getName() { 6 return this.name; 7 } 8} 9 10// bad 11class Rey extends Jedi { 12 constructor(...args) { 13 super(...args); 14 } 15} 16 17// good 18class Rey extends Jedi { 19 constructor(...args) { 20 super(...args); 21 this.name = 'Rey'; 22 } 23}
-
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.
1// bad 2class Foo { 3 bar() { return 1; } 4 bar() { return 2; } 5} 6 7// good 8class Foo { 9 bar() { return 1; } 10} 11 12// good 13class Foo { 14 bar() { return 2; } 15}
-
9.7 Class methods should use
this
or be made into a static method unless an external library or framework requires using specific non-static methods. Being an instance method should indicate that it behaves differently based on properties of the receiver. eslint:class-methods-use-this
1// bad 2class Foo { 3 bar() { 4 console.log('bar'); 5 } 6} 7 8// good - this is used 9class Foo { 10 bar() { 11 console.log(this.bar); 12 } 13} 14 15// good - constructor is exempt 16class Foo { 17 constructor() { 18 // ... 19 } 20} 21 22// good - static methods aren't expected to use this 23class Foo { 24 static bar() { 25 console.log('bar'); 26 } 27}
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.
1// bad 2const AirbnbStyleGuide = require('./AirbnbStyleGuide'); 3module.exports = AirbnbStyleGuide.es6; 4 5// ok 6import AirbnbStyleGuide from './AirbnbStyleGuide'; 7export default AirbnbStyleGuide.es6; 8 9// best 10import { es6 } from './AirbnbStyleGuide'; 11export default es6;
-
10.2 Do not use wildcard imports.
Why? This makes sure you have a single default export.
1// bad 2import * as AirbnbStyleGuide from './AirbnbStyleGuide'; 3 4// good 5import AirbnbStyleGuide from './AirbnbStyleGuide';
-
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.
1// bad 2// filename es6.js 3export { es6 as default } from './AirbnbStyleGuide'; 4 5// good 6// filename es6.js 7import { es6 } from './AirbnbStyleGuide'; 8export default es6;
-
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.
1// bad 2import foo from 'foo'; 3// … some other imports … // 4import { named1, named2 } from 'foo'; 5 6// good 7import foo, { named1, named2 } from 'foo'; 8 9// good 10import foo, { 11 named1, 12 named2, 13} from 'foo';
-
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.
1// bad 2let foo = 3; 3export { foo }; 4 5// good 6const foo = 3; 7export { foo };
-
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.
1// bad 2export function foo() {} 3 4// good 5export default function foo() {}
-
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.1// bad 2import foo from 'foo'; 3foo.init(); 4 5import bar from 'bar'; 6 7// good 8import foo from 'foo'; 9import bar from 'bar'; 10 11foo.init();
-
10.8 Multiline imports should be indented just like multiline array and object literals. eslint:
object-curly-newline
Why? The curly braces follow the same indentation rules as every other curly brace block in the style guide, as do the trailing commas.
1// bad 2import {longNameA, longNameB, longNameC, longNameD, longNameE} from 'path'; 3 4// good 5import { 6 longNameA, 7 longNameB, 8 longNameC, 9 longNameD, 10 longNameE, 11} from 'path';
-
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
.1// bad 2import fooSass from 'css!sass!foo.scss'; 3import barCss from 'style!css!bar.css'; 4 5// good 6import fooSass from 'foo.scss'; 7import barCss from 'bar.css';
-
10.10 Do not include JavaScript filename extensions eslint:
import/extensions
Why? Including extensions inhibits refactoring, and inappropriately hardcodes implementation details of the module you're importing in every consumer.
1// bad 2import foo from './foo.js'; 3import bar from './bar.jsx'; 4import baz from './baz/index.jsx'; 5 6// good 7import foo from './foo'; 8import bar from './bar'; 9import baz from './baz';
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.1const numbers = [1, 2, 3, 4, 5]; 2 3// bad 4let sum = 0; 5for (let num of numbers) { 6 sum += num; 7} 8sum === 15; 9 10// good 11let sum = 0; 12numbers.forEach((num) => { 13 sum += num; 14}); 15sum === 15; 16 17// best (use the functional force) 18const sum = numbers.reduce((total, num) => total + num, 0); 19sum === 15; 20 21// bad 22const increasedByOne = []; 23for (let i = 0; i < numbers.length; i++) { 24 increasedByOne.push(numbers[i] + 1); 25} 26 27// good 28const increasedByOne = []; 29numbers.forEach((num) => { 30 increasedByOne.push(num + 1); 31}); 32 33// best (keeping it functional) 34const increasedByOne = numbers.map((num) => num + 1);
-
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
.1// bad 2function * foo() { 3 // ... 4} 5 6// bad 7const bar = function * () { 8 // ... 9}; 10 11// bad 12const baz = function *() { 13 // ... 14}; 15 16// bad 17const quux = function*() { 18 // ... 19}; 20 21// bad 22function*foo() { 23 // ... 24} 25 26// bad 27function *foo() { 28 // ... 29} 30 31// very bad 32function 33* 34foo() { 35 // ... 36} 37 38// very bad 39const wat = function 40* 41() { 42 // ... 43}; 44 45// good 46function* foo() { 47 // ... 48} 49 50// good 51const foo = function* () { 52 // ... 53};
Properties
-
12.1 Use dot notation when accessing properties. eslint:
dot-notation
1const luke = { 2 jedi: true, 3 age: 28, 4}; 5 6// bad 7const isJedi = luke['jedi']; 8 9// good 10const isJedi = luke.jedi;
-
12.2 Use bracket notation
[]
when accessing properties with a variable.1const luke = { 2 jedi: true, 3 age: 28, 4}; 5 6function getProp(prop) { 7 return luke[prop]; 8} 9 10const isJedi = getProp('jedi');
-
12.3 Use exponentiation operator
**
when calculating exponentiations. eslint:prefer-exponentiation-operator
.1// bad 2const binary = Math.pow(2, 10); 3 4// good 5const 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
1// bad 2superPower = new SuperPower(); 3 4// good 5const superPower = new SuperPower();
-
13.2 Use one
const
orlet
declaration per variable or assignment. 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.1// bad 2const items = getItems(), 3 goSportsTeam = true, 4 dragonball = 'z'; 5 6// bad 7// (compare to above, and try to spot the mistake) 8const items = getItems(), 9 goSportsTeam = true; 10 dragonball = 'z'; 11 12// good 13const items = getItems(); 14const goSportsTeam = true; 15const 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 previously assigned variables.
1// bad 2let i, len, dragonball, 3 items = getItems(), 4 goSportsTeam = true; 5 6// bad 7let i; 8const items = getItems(); 9let dragonball; 10const goSportsTeam = true; 11let len; 12 13// good 14const goSportsTeam = true; 15const items = getItems(); 16let dragonball; 17let i; 18let 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.1// bad - unnecessary function call 2function checkName(hasName) { 3 const name = getName(); 4 5 if (hasName === 'test') { 6 return false; 7 } 8 9 if (name === 'test') { 10 this.setName(''); 11 return false; 12 } 13 14 return name; 15} 16 17// good 18function checkName(hasName) { 19 if (hasName === 'test') { 20 return false; 21 } 22 23 const name = getName(); 24 25 if (name === 'test') { 26 this.setName(''); 27 return false; 28 } 29 30 return name; 31}
-
13.5 Don’t chain variable assignments. eslint:
no-multi-assign
Why? Chaining variable assignments creates implicit global variables.
1// bad 2(function example() { 3 // JavaScript interprets this as 4 // let a = ( b = ( c = 1 ) ); 5 // The let keyword only applies to variable a; variables b and c become 6 // global variables. 7 let a = b = c = 1; 8}()); 9 10console.log(a); // throws ReferenceError 11console.log(b); // 1 12console.log(c); // 1 13 14// good 15(function example() { 16 let a = 1; 17 let b = a; 18 let c = a; 19}()); 20 21console.log(a); // throws ReferenceError 22console.log(b); // throws ReferenceError 23console.log(c); // throws ReferenceError 24 25// 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.1// bad 2 3const array = [1, 2, 3]; 4let num = 1; 5num++; 6--num; 7 8let sum = 0; 9let truthyCount = 0; 10for (let i = 0; i < array.length; i++) { 11 let value = array[i]; 12 sum += value; 13 if (value) { 14 truthyCount++; 15 } 16} 17 18// good 19 20const array = [1, 2, 3]; 21let num = 1; 22num += 1; 23num -= 1; 24 25const sum = array.reduce((a, b) => a + b, 0); 26const truthyCount = array.filter(Boolean).length;
-
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.1// bad 2const foo = 3 superLongLongLongLongLongLongLongLongFunctionName(); 4 5// bad 6const foo 7 = 'superLongLongLongLongLongLongLongLongString'; 8 9// good 10const foo = ( 11 superLongLongLongLongLongLongLongLongFunctionName() 12); 13 14// good 15const 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.
1// bad 2 3const some_unused_var = 42; 4 5// Write-only variables are not considered as used. 6let y = 10; 7y = 5; 8 9// A read for a modification of itself is not considered as used. 10let z = 0; 11z = z + 1; 12 13// Unused function arguments. 14function getX(x, y) { 15 return x; 16} 17 18// good 19 20function getXPlusY(x, y) { 21 return x + y; 22} 23 24const x = 1; 25const y = a + 2; 26 27alert(getXPlusY(x, y)); 28 29// 'type' is ignored even if unused because it has a rest property sibling. 30// This is a form of extracting an object that omits the specified keys. 31const { type, ...coords } = data; 32// '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.1// we know this wouldn’t work (assuming there 2// is no notDefined global variable) 3function example() { 4 console.log(notDefined); // => throws a ReferenceError 5} 6 7// creating a variable declaration after you 8// reference the variable will work due to 9// variable hoisting. Note: the assignment 10// value of `true` is not hoisted. 11function example() { 12 console.log(declaredButNotAssigned); // => undefined 13 var declaredButNotAssigned = true; 14} 15 16// the interpreter is hoisting the variable 17// declaration to the top of the scope, 18// which means our example could be rewritten as: 19function example() { 20 let declaredButNotAssigned; 21 console.log(declaredButNotAssigned); // => undefined 22 declaredButNotAssigned = true; 23} 24 25// using const and let 26function example() { 27 console.log(declaredButNotAssigned); // => throws a ReferenceError 28 console.log(typeof declaredButNotAssigned); // => throws a ReferenceError 29 const declaredButNotAssigned = true; 30}
-
14.2 Anonymous function expressions hoist their variable name, but not the function assignment.
1function example() { 2 console.log(anonymous); // => undefined 3 4 anonymous(); // => TypeError anonymous is not a function 5 6 var anonymous = function () { 7 console.log('anonymous function expression'); 8 }; 9}
-
14.3 Named function expressions hoist the variable name, not the function name or the function body.
1function example() { 2 console.log(named); // => undefined 3 4 named(); // => TypeError named is not a function 5 6 superPower(); // => ReferenceError superPower is not defined 7 8 var named = function superPower() { 9 console.log('Flying'); 10 }; 11} 12 13// the same is true when the function name 14// is the same as the variable name. 15function example() { 16 console.log(named); // => undefined 17 18 named(); // => TypeError named is not a function 19 20 var named = function named() { 21 console.log('named'); 22 }; 23}
-
14.4 Function declarations hoist their name and the function body.
1function example() { 2 superPower(); // => Flying 3 4 function superPower() { 5 console.log('Flying'); 6 } 7}
-
14.5 Variables, classes, and functions should be defined before they can be used. eslint:
no-use-before-define
Why? When variables, classes, or functions are declared after being used, it can harm readability since a reader won't know what a thing that's referenced is. It's much clearer for a reader to first encounter the source of a thing (whether imported from another module, or defined in the file) before encountering a use of the thing.
1// bad 2 3// Variable a is being used before it is being defined. 4console.log(a); // this will be undefined, since while the declaration is hoisted, the initialization is not 5var a = 10; 6 7// Function fun is being called before being defined. 8fun(); 9function fun() {} 10 11// Class A is being used before being defined. 12new A(); // ReferenceError: Cannot access 'A' before initialization 13class A { 14} 15 16// `let` and `const` are hoisted, but they don't have a default initialization. 17// The variables 'a' and 'b' are in a Temporal Dead Zone where JavaScript 18// knows they exist (declaration is hoisted) but they are not accessible 19// (as they are not yet initialized). 20 21console.log(a); // ReferenceError: Cannot access 'a' before initialization 22console.log(b); // ReferenceError: Cannot access 'b' before initialization 23let a = 10; 24const b = 5; 25 26 27// good 28 29var a = 10; 30console.log(a); // 10 31 32function fun() {} 33fun(); 34 35class A { 36} 37new A(); 38 39let a = 10; 40const b = 5; 41console.log(a); // 10 42console.log(b); // 5
-
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
1if ([0] && []) { 2 // true 3 // an array (even an empty one) is an object, objects will evaluate to true 4}
-
15.3 Use shortcuts for booleans, but explicit comparisons for strings and numbers.
1// bad 2if (isValid === true) { 3 // ... 4} 5 6// good 7if (isValid) { 8 // ... 9} 10 11// bad 12if (name) { 13 // ... 14} 15 16// good 17if (name !== '') { 18 // ... 19} 20 21// bad 22if (collection.length) { 23 // ... 24} 25 26// good 27if (collection.length > 0) { 28 // ... 29}
- 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.1// bad 2switch (foo) { 3 case 1: 4 let x = 1; 5 break; 6 case 2: 7 const y = 2; 8 break; 9 case 3: 10 function f() { 11 // ... 12 } 13 break; 14 default: 15 class C {} 16} 17 18// good 19switch (foo) { 20 case 1: { 21 let x = 1; 22 break; 23 } 24 case 2: { 25 const y = 2; 26 break; 27 } 28 case 3: { 29 function f() { 30 // ... 31 } 32 break; 33 } 34 case 4: 35 bar(); 36 break; 37 default: { 38 class C {} 39 } 40}
-
15.6 Ternaries should not be nested and generally be single line expressions. eslint:
no-nested-ternary
1// bad 2const foo = maybe1 > maybe2 3 ? "bar" 4 : value1 > value2 ? "baz" : null; 5 6// split into 2 separated ternary expressions 7const maybeNull = value1 > value2 ? 'baz' : null; 8 9// better 10const foo = maybe1 > maybe2 11 ? 'bar' 12 : maybeNull; 13 14// best 15const foo = maybe1 > maybe2 ? 'bar' : maybeNull;
-
15.7 Avoid unneeded ternary statements. eslint:
no-unneeded-ternary
1// bad 2const foo = a ? a : b; 3const bar = c ? true : false; 4const baz = c ? false : true; 5const quux = a != null ? a : b; 6 7// good 8const foo = a || b; 9const bar = !!c; 10const baz = !c; 11const quux = a ?? b;
- 15.8 When mixing operators, enclose th

No vulnerabilities found.

No security vulnerabilities found.