- Eslint and Prettier
- References
- Objects
- Arrays
- Destructuring
- Strings
- Functions
- Arrow Functions
- Modules
- Iterators and Generators
- Variables
- Comparison Operators & Equality
- Blocks
- Control Statements
- Comments
- Naming Conventions
Normally all projects use eslint and prettier, install the respective plugins in your favorite IDE.
-
If your project does not have a prettier configuration, use the basic configuration:
{ arrowParens: 'always', bracketSameLine: false, bracketSpacing: true, embeddedLanguageFormatting: 'auto', htmlWhitespaceSensitivity: 'css', insertPragma: false, jsxSingleQuote: false, printWidth: 100, proseWrap: 'preserve', quoteProps: 'as-needed', requirePragma: false, semi: true, singleQuote: true, tabWidth: 2, trailingComma: 'es5', useTabs: false, vueIndentScriptAndStyle: false, }
-
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.
// bad var a = 1; var b = 2; // good const a = 1; const b = 2;
-
If you must reassign references, use
let
instead ofvar
. eslint:no-var
Why?
let
is block-scoped rather than function-scoped likevar
.// bad var count = 1; if (true) { count += 1; } // good, use the let. let count = 1; if (true) { count += 1; }
-
Use the literal syntax for object creation. eslint:
no-new-object
// bad const item = new Object(); // good const item = {};
-
Use object method shorthand. eslint:
object-shorthand
// bad const atom = { value: 1, addValue: function (value) { return atom.value + value; }, }; // good const atom = { value: 1, addValue(value) { return atom.value + value; }, };
-
Use property value shorthand. eslint:
object-shorthand
Why? It is shorter and descriptive.
const lukeSkywalker = 'Luke Skywalker'; // bad const obj = { lukeSkywalker: lukeSkywalker, }; // good const obj = { lukeSkywalker, };
-
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'; // bad const obj = { episodeOne: 1, twoJediWalkIntoACantina: 2, lukeSkywalker, episodeThree: 3, mayTheFourth: 4, anakinSkywalker, }; // good const obj = { lukeSkywalker, anakinSkywalker, episodeOne: 1, twoJediWalkIntoACantina: 2, episodeThree: 3, mayTheFourth: 4, };
-
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.
// bad const bad = { 'foo': 3, 'bar': 4, 'data-blah': 5, }; // good const good = { foo: 3, bar: 4, 'data-blah': 5, };
-
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
// very bad const original = { a: 1, b: 2 }; const copy = Object.assign(original, { c: 3 }); // this mutates `original` ಠ_ಠ delete copy.a; // so does this // bad const original = { a: 1, b: 2 }; const copy = Object.assign({}, original, { c: 3 }); // copy => { a: 1, b: 2, c: 3 } // good const 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 }
-
Use the literal syntax for array creation. eslint:
no-array-constructor
// bad const items = new Array(); // good const items = [];
-
Use Array#push instead of direct assignment to add items to an array.
const someStack = []; // bad someStack[someStack.length] = 'abracadabra'; // good someStack.push('abracadabra');
-
Use array spreads
...
to copy arrays.// bad const len = items.length; const itemsCopy = []; let i; for (i = 0; i < len; i += 1) { itemsCopy[i] = items[i]; } // good const itemsCopy = [...items];
-
To convert an iterable object to an array, use spreads
...
instead ofArray.from
.const foo = document.querySelectorAll('.foo'); // good const nodes = Array.from(foo); // best const nodes = [...foo];
-
Use
Array.from
for converting an array-like object to an array.const arrLike = { 0: 'foo', 1: 'bar', 2: 'baz', length: 3 }; // bad const arr = Array.prototype.slice.call(arrLike); // good const arr = Array.from(arrLike);
-
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.
// bad function getFullName(user) { const firstName = user.firstName; const lastName = user.lastName; return `${firstName} ${lastName}`; } // good function getFullName(user) { const { firstName, lastName } = user; return `${firstName} ${lastName}`; } // best function getFullName({ firstName, lastName }) { return `${firstName} ${lastName}`; }
-
Use array destructuring. eslint:
prefer-destructuring
const arr = [1, 2, 3, 4]; // bad const first = arr[0]; const second = arr[1]; // good const [first, second] = arr;
-
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 function processInput(input) { // then a miracle occurs return [left, right, top, bottom]; } // the caller needs to think about the order of return data const [left, __, top] = processInput(input); // good function processInput(input) { // then a miracle occurs return { left, right, top, bottom }; } // the caller selects only the data they need const { left, top } = processInput(input);
-
Use single quotes
''
for strings. eslint:quotes
// bad const name = "Capt. Janeway"; // bad - template literals should contain interpolation or newlines const name = `Capt. Janeway`; // good const name = 'Capt. Janeway';
-
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 function sayHi(name) { return 'How are you, ' + name + '?'; } // bad function sayHi(name) { return ['How are you, ', name, '?'].join(); } // bad function sayHi(name) { return `How are you, ${ name }?`; } // good function sayHi(name) { return `How are you, ${name}?`; }
-
Do not unnecessarily escape characters in strings. eslint:
no-useless-escape
Why? Backslashes harm readability, thus they should only be present when necessary.
// bad const foo = '\'this\' \i\s \"quoted\"'; // good const foo = '\'this\' is "quoted"'; const foo = `my name is '${name}'`;
-
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 function foo() { // ... } // bad const foo = function () { // ... }; // good // lexical name distinguished from the variable-referenced invocation(s) const short = function longUniqueMoreDescriptiveLexicalFoo() { // ... };
-
Never name a parameter
arguments
. This will take precedence over thearguments
object that is given to every function scope.// bad function foo(name, options, arguments) { // ... } // good function foo(name, options, args) { // ... }
-
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 function concatenateAll() { const args = Array.prototype.slice.call(arguments); return args.join(''); } // good function concatenateAll(...args) { return args.join(''); }
-
Use default parameter syntax rather than mutating function arguments.
// really bad function handleThings(opts) { // 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 function handleThings(opts) { if (opts === void 0) { opts = {}; } // ... } // good function handleThings(opts = {}) { // ... }
-
Always put default parameters last. eslint:
default-param-last
// bad function handleThings(opts = {}, name) { // ... } // good function handleThings(name, opts = {}) { // ... }
-
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 function f1(a) { a = 1; // ... } function f2(a) { if (!a) { a = 1; } // ... } // good function f3(a) { const b = a || 1; // ... } function f4(a = 1) { // ... }
-
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
.// bad const x = [1, 2, 3, 4, 5]; console.log.apply(console, x); // good const x = [1, 2, 3, 4, 5]; console.log(...x); // bad new (Function.prototype.bind.apply(Date, [null, 2016, 8, 5])); // good new Date(...[2016, 8, 5]);
-
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 function foo(bar, baz, quux) { // ... } // good function foo( bar, baz, quux, ) { // ... } // bad console.log(foo, bar, baz); // good console.log( foo, bar, baz, );
-
When developing functions or methods that require the use of more than three arguments, consider grouping these arguments into one object. This practice helps improve code readability and maintainability. The following are the advantages of this strategy.
// bad function createUser(name, age, email, isAdmin, isActive) { // ... } // good function createUser(userDetails) { // ... } // Example of function call const user = createUser({ name: "Pepe", age: 30, email: "[email protected]", isAdmin: false, isActive: true, });
-
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.
// bad [1, 2, 3].map(function (x) { const y = x + 1; return x * y; }); // good [1, 2, 3].map((x) => { const y = x + 1; return x * y; });
-
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.
// bad [1, 2, 3].map((number) => { const nextNumber = number + 1; `A string containing the ${nextNumber}.`; }); // good [1, 2, 3].map((number) => `A string containing the ${number + 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.
// bad const AirbnbStyleGuide = require('./AirbnbStyleGuide'); module.exports = AirbnbStyleGuide.es6; // ok import AirbnbStyleGuide from './AirbnbStyleGuide'; export default AirbnbStyleGuide.es6; // best import { es6 } from './AirbnbStyleGuide'; export default es6;
-
Do not use wildcard imports.
Why? This makes sure you have a single default export.
// bad import * as AirbnbStyleGuide from './AirbnbStyleGuide'; // good import AirbnbStyleGuide from './AirbnbStyleGuide';
-
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 export { es6 as default } from './AirbnbStyleGuide'; // good // filename es6.js import { es6 } from './AirbnbStyleGuide'; export default es6;
-
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 import foo from 'foo'; // … some other imports … // import { named1, named2 } from 'foo'; // good import foo, { named1, named2 } from 'foo'; // good import foo, { named1, named2, } from 'foo';
-
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 import foo from 'foo'; foo.init(); import bar from 'bar'; // good import foo from 'foo'; import bar from 'bar'; foo.init();
-
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.
// bad import foo from './foo.js'; import bar from './bar.jsx'; import baz from './baz/index.jsx'; // good import foo from './foo'; import bar from './bar'; import baz from './baz';
-
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]; // bad let sum = 0; for (let num of numbers) { sum += num; } sum === 15; // good let sum = 0; numbers.forEach((num) => { sum += num; }); sum === 15; // best (use the functional force) const sum = numbers.reduce((total, num) => total + num, 0); sum === 15; // bad const increasedByOne = []; for (let i = 0; i < numbers.length; i++) { increasedByOne.push(numbers[i] + 1); } // good const increasedByOne = []; numbers.forEach((num) => { increasedByOne.push(num + 1); }); // best (keeping it functional) const increasedByOne = numbers.map((num) => num + 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
// bad superPower = new SuperPower(); // good const superPower = new SuperPower();
-
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.
// bad let i, len, dragonball, items = getItems(), goSportsTeam = true; // bad let i; const items = getItems(); let dragonball; const goSportsTeam = true; let len; // good const goSportsTeam = true; const items = getItems(); let dragonball; let i; let length;
-
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.// bad const array = [1, 2, 3]; let num = 1; num++; --num; let sum = 0; let truthyCount = 0; for (let i = 0; i < array.length; i++) { let value = array[i]; sum += value; if (value) { truthyCount++; } } // good const array = [1, 2, 3]; let num = 1; num += 1; num -= 1; const sum = array.reduce((a, b) => a + b, 0); const truthyCount = array.filter(Boolean).length;
-
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.
// bad var 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. function getX(x, y) { return x; } // good function getXPlusY(x, y) { return x + y; } var x = 1; var y = a + 2; alert(getXPlusY(x, y)); // '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.
-
Use
===
and!==
over==
and!=
. eslint:eqeqeq
-
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 }
-
Use shortcuts for booleans, but explicit comparisons for strings and numbers.
// bad if (isValid === true) { // ... } // good if (isValid) { // ... } // bad if (name !== '') { // ... } // good if (name) { // ... } // bad if (collection.length > 0) { // ... } // good if (collection.length) { // ... }
-
Ternaries should not be nested and generally be single line expressions. eslint:
no-nested-ternary
// bad const foo = maybe1 > maybe2 ? "bar" : value1 > value2 ? "baz" : null; // split into 2 separated ternary expressions const maybeNull = value1 > value2 ? 'baz' : null; // better const foo = maybe1 > maybe2 ? 'bar' : maybeNull; // best const foo = maybe1 > maybe2 ? 'bar' : maybeNull;
-
Avoid unneeded ternary statements. eslint:
no-unneeded-ternary
// bad const foo = a ? a : b; const bar = c ? true : false; const baz = c ? false : true; // good const foo = a || b; const bar = !!c; const baz = !c;
-
When mixing operators, enclose them in parentheses. The only exception is the standard arithmetic operators:
+
,-
, and**
since their precedence is broadly understood. We recommend enclosing/
and*
in parentheses because their precedence can be ambiguous when they are mixed. eslint:no-mixed-operators
Why? This improves readability and clarifies the developer’s intention.
// bad const foo = a && b < 0 || c > 0 || d + 1 === 0; // bad const bar = a ** b - 5 % d; // bad // one may be confused into thinking (a || b) && c if (a || b && c) { return d; } // bad const bar = a + b / c * d; // good const foo = (a && b < 0) || c > 0 || (d + 1 === 0); // good const bar = a ** b - (5 % d); // good if (a || (b && c)) { return d; } // good const bar = a + (b / c) * d;
-
Use braces with all multiline blocks. eslint:
nonblock-statement-body-position
// bad if (test) return false; // good if (test) return false; // good if (test) { return false; } // bad function foo() { return false; } // good function bar() { return false; }
-
If you’re using multiline blocks with
if
andelse
, putelse
on the same line as yourif
block’s closing brace. eslint:brace-style
// bad if (test) { thing1(); thing2(); } else { thing3(); } // good if (test) { thing1(); thing2(); } else { thing3(); }
-
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 function foo() { if (x) { return x; } else { return y; } } // bad function cats() { if (x) { return x; } else if (y) { return y; } } // bad function dogs() { if (x) { return x; } else { if (y) { return y; } } } // good function foo() { if (x) { return x; } return y; } // good function cats() { if (x) { return x; } if (y) { return y; } } // good function dogs(x) { if (x) { if (z) { return y; } } else { return z; } }
-
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.
// bad if ((foo === 123 || bar === 'abc') && doesItLookGoodWhenItBecomesThatLong() && isThisReallyHappening()) { thing1(); } // bad if (foo === 123 && bar === 'abc') { thing1(); } // bad if (foo === 123 && bar === 'abc') { thing1(); } // bad if ( foo === 123 && bar === 'abc' ) { thing1(); } // good if ( foo === 123 && bar === 'abc' ) { thing1(); } // good if ( (foo === 123 || bar === 'abc') && doesItLookGoodWhenItBecomesThatLong() && isThisReallyHappening() ) { thing1(); } // good if (foo === 123 && bar === 'abc') { thing1(); }
-
Don't use selection operators in place of control statements.
// bad !isRunning && startRunning(); // good if (!isRunning) { startRunning(); }
-
The first function is a bad practice because it uses an else if string that makes the code more difficult to read and can complicate the addition or modification of conditions in the future. The second approach is a better practice because it improves clarity and maintainability: by eliminating the else, each condition is handled independently, making the code more readable and facilitating future modifications.
let isFirstStepWorking = true; let isSecondStepWorking = true; let isThirdStepWorking = true; let isFourthStepWorking = false; // bad const workingSteps = () => { if (isFirstStepWorking === true) { if (isSecondStepWorking === true) { if (isThirdStepWorking === true) { if (isFourthStepWorking === true) { return "Working properly!"; } else { return "Fourth step broken."; } } else { return "Third step broken."; } } else { return "Second step broken."; } } else { return "First step broken."; } } // good const workingSteps = () => { if (!isFirstStepWorking) return "First step broken."; if (!isSecondStepWorking) return "Second step broken."; if (!isThirdStepWorking) return "Third step broken."; if (!isFourthStepWorking) return "Fourth step broken."; return "Working properly!"; } // bad const getPayAmount = ({ isDead = false, isSeparated = true, isRetired = false }) => { let result; if ( isDead ) { result = 1500; } else { if ( isSeparated ) { result = 2500; } else { if ( isRetired ) { result = 3000; } else { result = 4000; } } } return result; } // good const getPayAmount = ({ isDead = false, isSeparated = true, isRetired = false }) => { if ( isDead ) return 1500; if ( isSeparated ) return 2500; if ( isRetired ) return 3000; return 4000; } // best const getPayAmount = ({ isDead = false, isSeparated = true, isRetired = false }) => { if ( isDead ) return 1500; if ( isSeparated ) return 2500; return isRetired ? 3000 : 4000; }
-
Each of the three versions of the getFruitsByColor function aims to do the same thing: return a list of fruits based on the given color or throw an error if the color is not among the expected ones. However, they differ in their clarity, brevity, and maintainability.
Version (
'bad'
,if-else
)Pros: This version is straightforward and easy to understand. Cons: However, using multiple if-else statements can make the code harder to read, especially if more colors and conditions are added in the future. As the list grows, it becomes more cumbersome to follow the logic and maintain the code.
Version (
'good'
,switch-case
)Pros: Using a switch slightly improves readability compared to multiple if-else statements, and it's a bit easier to maintain as it has a clearer structure for handling multiple conditions based on a single variable. Cons: Still, adding or removing colors requires changing the switch structure, which could be seen as more work than simply adding or removing properties from an object.
Version (
'best'
,lookup object
)Pros: This version is more concise and easier to maintain. The logic of mapping colors to fruits is managed through a literal object, which makes adding or removing colors as easy as modifying the fruitsByColor object. There are no complex control flow structures (like if or switch), and the line that throws the error is very short and clear. Efficiency: Accessing an object's property is generally faster than a switch statement or multiple if-else statements, especially if the list of cases is long. Cons: One might argue that for someone not accustomed to working with operators like ?? or the error handling style using throw in expressions, this version could be slightly less readable. However, this is a common pattern in modern TypeScript and JavaScript.
// bad const getFruitsByColor = ( color ) => { if ( color === 'red' ) { return ['manzana','fresa']; } else if ( color === 'yellow') { return ['piña','banana']; } else if ( color === 'purple') { return ['moras','uvas'] } else { throw Error('the color must be: red, yellow, purple'); } } // good const getFruitsByColor = ( color ) => { switch( color ) { case 'red': return ['manzana','fresa']; case 'yellow': return ['piña','banana']; case 'purple': return ['moras','uvas']; default: throw Error('the color must be: red, yellow, purple'); } } // best const getFruitsByColor = ( color ) => { const fruitsByColor = { red: ['manzana','fresa'], yellow: ['piña','banana'], purple: ['moras','uvas'], }; return fruitsByColor[color] ?? throw new Error('the color must be: red, yellow, purple'); }
-
Version (
'bad'
)The first block of code (bad) uses multiple logical operators || to compare the variable color with a list of values. This makes the code:
Verbose: There's a lot of repeated text, which makes the code longer and less readable. Hard to maintain: If you need to add or remove a color, you have to modify the condition and make sure you do not make mistakes while manipulating the logical operators.
Version (
'good'
)The second block of code (good) improves upon the former by utilizing the Array.includes() method. This makes the code:
More readable: By placing all the colors into an array and using includes(), the code's purpose becomes clearer. Easier to maintain: Adding or removing colors from the array is straightforward and less error-prone.
Version (
'best' first version
)The third block of code (best) further improves by reorganizing the logic:
Less complex: It inverts the logic of the condition, returning immediately if the color is not included, which reduces a level of nesting and enhances clarity. Cleaner code: Eliminates the unnecessary else because if the condition is met, the function ends with a return.
Version (
'best'
)The last version uses a ternary expression, which is a concise way to write an if-else statement.
// bad const colorForRainbow = (color) => { if ( color === "red" || color === "orange" || color === "yellow" || color === "green" || color === "blue" || color === "indigo" || color === "violet" ) { return "yes, it is a valid color"; } else { return "no, it is not a valid color"; } }; // good const colorForRainbow = (color) => { if ( ["red", "orange", "yellow", "green", "blue", "indigo", "violet"].includes( color ) ) { return "yes, it is a valid color"; } else { return "no, it is not a valid color"; } }; // best const colorForRainbow = (color) => { if ( !["red", "orange", "yellow", "green", "blue", "indigo", "violet"].includes( color ) ) { return "no, it is not a valid color"; } return "yes, it is a valid color"; }; // best const colorForRainbow = (color) => ["red", "orange", "yellow", "green", "blue", "indigo", "violet"].includes( color ) ? "yes, it is a valid color" : "no, it is not a valid color";
-
Use
/** ... */
for multiline comments.// bad // make() returns a new element // based on the passed in tag name // // @param {String} tag // @return {Element} element function make(tag) { // ... return element; } // good /** * make() returns a new element * based on the passed-in tag name */ function make(tag) { // ... return element; }
-
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.// bad const active = true; // is current tab // good // is current tab const active = true; // bad function getType() { console.log('fetching type...'); // set the default type to 'no type' const type = this.type || 'no type'; return type; } // good function getType() { console.log('fetching type...'); // set the default type to 'no type' const type = this.type || 'no type'; return type; } // also good function getType() { // set the default type to 'no type' const type = this.type || 'no type'; return type; }
-
Start all comments with a space to make it easier to read. eslint:
spaced-comment
// bad //is current tab const active = true; // good // is current tab const active = true; // bad /** *make() returns a new element *based on the passed-in tag name */ function make(tag) { // ... return element; } // good /** * make() returns a new element * based on the passed-in tag name */ function make(tag) { // ... return element; }
-
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
. -
Use
// FIXME:
to annotate problems.class Calculator extends Abacus { constructor() { super(); // FIXME: shouldn’t use a global here total = 0; } }
-
Use
// TODO:
to annotate solutions to problems.class Calculator extends Abacus { constructor() { super(); // TODO: total should be configurable by an options param this.total = 0; } }
-
Avoid single letter names. Be descriptive with your naming. eslint:
id-length
// bad function q() { // ... } // good function query() { // ... }
-
Use camelCase when naming objects, functions, and instances. eslint:
camelcase
// bad const OBJEcttsssss = {}; const this_is_my_object = {}; function c() {} // good const thisIsMyObject = {}; function thisIsMyFunction() {}
-
Use PascalCase only when naming constructors or classes. eslint:
new-cap
// bad function user(options) { this.name = options.name; } const bad = new user({ name: 'nope', }); // good class User { constructor(options) { this.name = options.name; } } const good = new User({ name: 'yup', });
-
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.
// bad this.__firstName__ = 'Panda'; this.firstName_ = 'Panda'; this._firstName = 'Panda'; // good this.firstName = 'Panda'; // good, in environments where WeakMaps are available // see https://kangax.github.io/compat-table/es6/#test-WeakMap const firstNames = new WeakMap(); firstNames.set(this, 'Panda');
-
A base filename should exactly match the name of its default export.
// file 1 contents class CheckBox { // ... } export default CheckBox; // file 2 contents export default function fortyTwo() { return 42; } // file 3 contents export default function insideDirectory() {} // in some other file // bad import CheckBox from './checkBox'; // PascalCase import/export, camelCase filename import FortyTwo from './FortyTwo'; // PascalCase import/filename, camelCase export import InsideDirectory from './InsideDirectory'; // PascalCase import/filename, camelCase export // bad import CheckBox from './check_box'; // PascalCase import/export, snake_case filename import forty_two from './forty_two'; // snake_case import/filename, camelCase export import inside_directory from './inside_directory'; // snake_case import, camelCase export import index from './inside_directory/index'; // requiring the index file explicitly import insideDirectory from './insideDirectory/index'; // requiring the index file explicitly // good import CheckBox from './CheckBox'; // PascalCase export/import/filename import fortyTwo from './fortyTwo'; // camelCase export/import/filename import insideDirectory from './insideDirectory'; // camelCase export/import/directory name/implicit "index" // ^ supports both insideDirectory.js and insideDirectory/index.js
-
Use camelCase when you export-default a function. Your filename should be identical to your function’s name.
function makeStyleGuide() { // ... } export default makeStyleGuide;
-
Use PascalCase when you export a constructor / class / singleton / function library / bare object.
const AirbnbStyleGuide = { es6: { }, }; export default AirbnbStyleGuide;
-
Acronyms and initialisms should always be all uppercased, or all lowercased.
Why? Names are for readability, not to appease a computer algorithm.
// bad import SmsContainer from './containers/SmsContainer'; // bad const HttpRequests = [ // ... ]; // good import SMSContainer from './containers/SMSContainer'; // good const HTTPRequests = [ // ... ]; // also good const httpRequests = [ // ... ]; // best import TextMessageContainer from './containers/TextMessageContainer'; // best const requests = [ // ... ];
-
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.
// bad const PRIVATE_VARIABLE = 'should not be unnecessarily uppercased within a file'; // bad export const THING_TO_BE_CHANGED = 'should obviously not be uppercased'; // bad export let REASSIGNABLE_VARIABLE = 'do not use let with uppercase variables'; // --- // allowed but does not supply semantic value export const apiKey = 'SOMEKEY'; // better in most cases export const API_KEY = 'SOMEKEY'; // --- // bad - unnecessarily uppercases key while adding no semantic value export const MAPPING = { KEY: 'value' }; // good export const MAPPING = { key: 'value' };
- What about all