PublicisSapient Javascript Styleguide
A Javascript styleguide written from an enterprise perspective.
Table of Contents
Accessors
MDN web docs:
ESLint rules:
Accessors are more commonly referred to as getters and setters. The get
and set
syntax binds an object property to a function that will be called when that property is looked up or assigned a value.
This pattern looks promising but has too many drawbacks to be used on a large project. Spelling mistakes will not trigger errors with set
calls. This can be avoided by using normal functions instead of getters and setters.
// bad { thisfirstName = 'Ada'; thislastName = 'Lovelace'; } { return ` `; } { const names = value; thisfirstName = names0; thislastName = names1; } var user = ; // An error will be thrown for spelling mistakes on getters // TypeError: undefined is not a function console; // However since an object property can be named anything it will not be // thrown on setters userfulName = 'Edith Clarke'; // good { thisfirstName = 'Valerie'; thislastName = 'Taylor'; } { return ` `; } { const names = value; thisfirstName = names0; thislastName = names1; } var user = ; // An error will be thrown for spelling mistakes on getters // TypeError: undefined is not a function user; // An error will also be thrown here as well user; // And it's more obvious that you're calling a function like this user;
Arrays
MDN web docs:
ESLint rules:
array-callback-return
no-sparse-arrays
array-bracket-newline
array-bracket-spacing
array-element-newline
no-array-constructor
Create arrays using the literal notation instead of the constructor.
// bad const planets = ; // good const planets = ;
Don't use spaces after open and before close brackets when creating an array.
// bad const planets = 'Mercury' 'Venus' 'Earth' ; // good const planets = 'Mercury' 'Venus' 'Earth';
If there are more than 5 elements in an array use line breaks to put each value on their own line.
// bad const planets = 'Mercury' 'Venus' 'Earth' 'Mars' 'Jupiter' 'Saturn'; // bad const planets = 'Mercury' 'Venus' 'Earth' 'Mars' 'Jupiter' 'Saturn' ; // good const planets = 'Mercury' 'Venus' 'Earth' 'Mars' 'Jupiter' 'Saturn' ; // good const planets = name: 'Mercury' color: 'red' name: 'Venus' color: 'blue' name: 'Mars' color: 'red' name: 'Earth' color: 'blue' name: 'Jupiter' color: 'brown' name: 'Saturn' color: 'orange' ;
Get the value of an item in an Array by using the index.
const venus = planets1; const earth = planets2;
Loop through Arrays using the forEach
method
planets;
Add items to an Array using the push
method.
planets;
Combine two or more Arrays using ... notation.
const array1 = 1 2 3; const array2 = 4 5 6; const combinedArray = ...array1 ...array2; // expected output: [1, 2, 3, 4, 5, 6]
Create an Array from any array-like iterable using from
. Array-like iterables include things like: String
, Set
, Map
, and arguments
.
// create an array from a String const letters = Array; // expected output: ['m', 'a', 'r', 's']
Use a return statement with Array methods every
, filter
, find
, findIndex
, map
, reduce
, reduceRight
, some
, sort
.
const numbers = 1 2 3; // check if all the items in the Array are less than 10 with .every() const allLessThanTen = numbers; // expected output: true // Create a new Array with all the items in the Array that are greater than // 1 with .filter() const greaterThanOne = numbers; // expected output: [2, 3] // find the first item greater than 1 with .find() const first = numbers; // expected output: 2 // find the index of the first item greater than 1 with .findIndex() const firstIndex = numbers; // expected output: 1 // Create a new Array with double all the numbers in the Array with .map() const doubleNumbers = numbers; // expected output: [2, 4, 6] // calculate the sum of all items using .reduce() const sum = numbers; // expected output: 6 // check if at least one item in the Array is less than 10 with .some() const someLessThanTen = numbers; // expected output: true // sort a list of words by their length with .sort() const sortedWords = 'Gladys' 'Mae' 'West'; // expected output: ['Mae', 'West', 'Gladys']
Strings
MDN Web Docs:
ESLint Rules:
quotes
no-multi-str
prefer-template
template-curly-spacing
no-useless-escape
no-template-curly-in-string
Use single quotes '' for strings.
// badconst name = "Ada Lovelace"; // goodconst name = 'Grace Hopper'; // good - this applies to strings in other places like import and require statements as well;const myOtherModule = ;
Really long strings should be written as a single line and leave any line wrapping to the IDE or code editor.
// badconst melbaRoyMouton = 'Melba Roy Mouton (1929-1990) was an African-American \woman who served as Assistant Chief of Research Programs at NASA\'s Trajectory \and Geodynamics Division in the 1960s and headed a group of NASA \mathematicians called "computers". Starting as a mathematician, she was head \mathematician for Echo Satellites 1 and 2, and she worked up to being a Head \Computer Programmer and then Program Production Section Chief at Goddard Space \Flight Center.'; // badconst dorothyVaughan = 'Dorothy Johnson Vaughan (September 20, 1910 – November 10, 2008) ' + 'was an African American mathematician and human computer who worked for the National ' + 'Advisory Committee for Aeronautics (NACA), and NASA, at Langley Research Center in ' + 'Hampton, Virginia. In 1949, she became acting supervisor of the West Area Computers, ' + 'the first African-American woman to supervise a group of staff at the center.'; // goodconst katherineJohnson = 'Katherine Coleman Goble Johnson (born August 26, 1918) is an American mathematician whose calculations of orbital mechanics as a NASA employee were critical to the success of the first and subsequent U.S. crewed spaceflights. During her 35-year career at NASA and its predecessor, she earned a reputation for mastering complex manual calculations and helped pioneer the use of computers to perform the tasks. The space agency noted her "historical role as one of the first African-American women to work as a NASA scientist".';
Use template strings instead of concatenation when building up strings programatically.
const astronaut = 'Ellen Ochoa'; // bad - don't use string literals templates if you don't have any embedded expressionsconst astronaut = `Ellen Ochoa`; // badconst goal = 'When I grow up I want to be an astronaut like ' + astronaut + '!'; // badconst goal = 'When I grow up' 'I want to be' 'an astronaut' 'like' astronaut '!'; // goodconst goal = `When I grow up I want to be an astronaut like !`;
Do not use template string notation inside of regular strings. The output is not technically wrong however it is more than likely an unintentional mistake.
const astronaut = 'Jenni Sydey'; // badconst goal = 'When I grow up I want to be like ${astronaut}!';// expected output: 'When I grow up I want to be like ${astronaut}!' // goodconst goal = `When I grow up I want to be like !`;// expectec output: 'When I grow up I want to be like Jenni Sydey!'
Only escape characters in strings that actually require escaping.
// bad - the double quotes don't need escapingconst anneMcClain = 'Anne\'s \call sign is \"Annimal\"'; // goodconst anneMcClain = 'Anne\'s call sign is "Annimal"';
Global
ESLint Rules:
Never use eval() in any circumstance. It is an enormous security risk.
// badconsole;// expected output: 4 // badconsole;// expected output: 2 + 2 // badconsole;// expected output: true
Whitespace
ESLint rules:
- TODO: spaces/tabs (
indent
) space-before-blocks
space-before-function-paren
keyword-spacing
space-infix-ops
comma-spacing
no-multiple-empty-lines
Use a space before the opening brace of a block.
// bad { console; } // good { console; }
Do not use a space between the argument list and the function name in function calls and declarations.
// bad { console; } // good { console; }
Use a space before opening parenthesis in control statements (if
, while
, etc.).
// bad ifcondition ... // good if condition ...
Use spaces between operators.
// bad const a=b+10; // good const a = b + 10;
Use a space after commas.
// bad const list = 1234 { ... } // good const list = 1 2 3 4 { ... }
Do not leave multiple blank lines.
// bad const value = 'hello world'; console; // good const value = 'hello world'; console;
Leave a blank line between a block and the next statement.
// bad if valid return value; return message; // good if valid return value; return message;
// bad const dog = { } { } ; return obj; // good const dog = { } { } ; return obj;
Comparison Operators & Equality
MDN web docs:
ESLint rules:
Use ===
and !==
over ==
and !=
Use shortcuts for booleans, but explicit comparisons for strings and numbers
// bad if isLoaded === true ... // good if isLoaded ... // bad if value ... // good if value !== '' ... // bad if itemslength ... // good if itemslength > 0 ...
Do not nest ternary expressions
// bad const thing = foo ? bar : baz === qux ? quxx : foobar;
// good const thing = foo ? bar : foobar; // good let thing; if foo thing = bar; else if baz === qux thing = quxx; else thing = foobar;
Do not use ternary expressions when simpler alternatives exist
// bad const isEven = value % 2 === 0 ? true : false; // good const isEven = value % 2 === 0; // bad const isOdd = value % 2 === 0 ? false : true; // good const isOdd = value % 2 !== 0;
// bad const value = newNumber ? newNumber : 1; // good const value = newNumber || 1;