migme JavaScript Style Guide
migme's approach to JavaScript. Semi-based on Airbnb's Style Guide and Standard
Table of Contents
- Types
- References
- Objects
- Arrays
- Destructuring
- Strings
- Functions
- Arrow Functions
- Constructors
- Modules
- Iterators and Generators
- Properties
- Variables
- Hoisting
- Comparison Operators & Equality
- Blocks
- Comments
- Whitespace
- Commas
- Semicolons
- Type Casting & Coercion
- Naming Conventions
- Accessors
- Events
- jQuery
- ECMAScript 5 Compatibility
- ECMAScript 6 Styles
- Testing
- Performance
- Resources
- License
Types
-
1.1 Primitives: When you access a primitive type you work directly on its value.
string
number
boolean
null
undefined
const foo = 1let bar = foobar = 42console // => 1, 42 -
1.2 Complex: When you access a complex type you work on a reference to its value.
object
array
function
const foo = 1 2const bar = foobar0 = 42console // => 42, 42
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 = 1var b = 2 // goodconst a = 1const b = 2
-
2.2 If you must reassign references, use
let
instead ofvar
. eslint:no-var
jscs:disallowVar
Why?
let
is block-scoped rather than function-scoped likevar
.// badvar count = 1if truecount += 1// good, use the let.let count = 1if 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 = 1const b = 1console // ReferenceErrorconsole // ReferenceError
Objects
- 3.1 Use the literal syntax for object creation. eslint:
no-new-object
// badconst item = // goodconst item = {}
-
3.2 If your code will be executed in browsers in script context, don't use reserved words as keys. It won't work in IE8. More info. It’s OK to use them in ES6 modules and server-side code. jscs:
disallowIdentifierNames
// badconst superman =default: clark: 'kent'private: true// goodconst superman =defaults: clark: 'kent'hidden: true -
3.3 Use readable synonyms in place of reserved words. jscs:
disallowIdentifierNames
// badconst superman =class: 'alien'// badconst superman =klass: 'alien'// goodconst superman =type: 'alien'
-
3.4 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.5 Use object method shorthand. eslint:
object-shorthand
jscs:requireEnhancedObjectLiterals
// badconst atom =value: 1{return atomvalue + value}// goodconst atom =value: 1{return atomvalue + value}
-
3.6 Use property value shorthand. eslint:
object-shorthand
jscs:requireEnhancedObjectLiterals
Why? It is shorter to write and descriptive.
const lukeSkywalker = 'Luke Skywalker'// badconst obj =lukeSkywalker: lukeSkywalker// goodconst obj =lukeSkywalker -
3.7 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.8 Only quote properties that are invalid identifiers. eslint:
quote-props
jscs:disallowQuotedKeysInObjects
Why? In general we consider it subjectively easier to read. It improves syntax highlighting, and is also more easily optimised by many JS engines.
// badconst bad = 'foo': 3 'bar': 4 'data-blah': 5 // goodconst good = foo: 3 bar: 4 'data-blah': 5
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 = itemslengthconst itemsCopy =let ifor i = 0; i < len; i++itemsCopyi = itemsi// goodconst itemsCopy = ...items -
4.4 To convert an array-like object to an array, use Array#from.
const foo = documentconst nodes = Array -
4.5 Use return statements in array method callbacks. It's ok to omit the return if the function body consists of a single statement following 8.2. eslint:
array-callback-return
// good1 2 3// good1 2 3// badconst flat = {}0 1 2 3 4 5// goodconst flat = {}0 1 2 3 4 5// badinbox// goodinbox
Destructuring
-
5.1 Use object destructuring when accessing and using multiple properties of an object. jscs:
requireObjectDestructuring
Why? Destructuring saves you from creating temporary references for those properties.
// bad{const firstName = userfirstNameconst lastName = userlastNamereturn ` `}// good{const firstName lastName = userreturn ` `}// best{return ` `} -
5.2 Use array destructuring. jscs:
requireArrayDestructuring
const arr = 1 2 3 4// badconst first = arr0const 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 right =
Strings
-
6.1 Use single quotes
''
for strings. eslint:quotes
jscs:validateQuoteMarks
// badconst name = "Malcolm Reynolds"// goodconst name = 'Malcolm Reynolds' -
6.2 Strings that cause the line to go over 100 characters should be written across multiple lines using string concatenation.
-
6.3 Note: If overused, long strings with concatenation could impact performance. jsPerf & Discussion.
// 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.4 When programmatically building up strings, use template strings instead of concatenation. eslint:
prefer-template
template-curly-spacing
jscs:requireTemplateStrings
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 Never use
eval()
on a string, it opens too many vulnerabilities.
Functions
-
7.1 Use function declarations instead of function expressions. jscs:
requireFunctionDeclarations
Why? Function declarations are named, so they're easier to identify in call stacks. Also, the whole body of a function declaration is hoisted, whereas only the reference of a function expression is hoisted. This rule makes it possible to always use Arrow Functions in place of function expressions.
// badconst foo = {}// good{} -
7.2 Immediately invoked function expressions: eslint:
wrap-iife
jscs:requireParenthesesAroundIIFE
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. Read ECMA-262's note on this issue.// badif currentUser{console}// goodlet testif currentUser{console} -
7.5 Never name a parameter
arguments
. This will take precedence over thearguments
object that is given to every function scope.// bad{// ...stuff...}// good{// ...stuff...}
-
7.6 Never use
arguments
, opt to use rest syntax...
instead.prefer-rest-params
Why?
...
is explicit about which arguments you want pulled. Plus rest arguments are a real Array and not Array-like likearguments
.// bad{const args = Arrayprototypeslicereturn 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.
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.
Why? Consistency is good.
// 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 optimisation issues, especially in V8.// bad{a = 1}{if !a a = 1}// good{const b = a || 1}{}
Arrow Functions
-
8.1 When you must use function expressions (as when passing an anonymous function), use arrow function notation. eslint:
prefer-arrow-callback
,arrow-spacing
jscs:requireArrowFunctions
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 function declaration.
// bad1 2 3// good1 2 3 -
8.2 If the function body consists of a single expression, omit the braces and use the implicit return. Otherwise, keep the braces and use a
return
statement. eslint:arrow-parens
,arrow-body-style
jscs:disallowParenthesesAroundArrowParam
,requireShorthandArrowFunctions
Why? Syntactic sugar. It reads well when multiple functions are chained together.
Why not? If you plan on returning an object.
// bad1 2 3// good1 2 3// good1 2 3 -
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.
// bad1 2 3// good1 2 3 -
8.4 If your function takes a single argument and doesn’t use braces, omit the parentheses. Otherwise, always include parentheses around arguments. eslint:
arrow-parens
jscs:disallowParenthesesAroundArrowParam
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 = { return itemheight > 256 ? itemlargeSize : itemsmallSize }
Constructors
-
9.1 Always use
class
. Avoid manipulatingprototype
directly.Why?
class
syntax is more concise and easier to reason about.// bad{this_queue = ...contents}Queueprototype {const value = this_queue0this_queuereturn value}// good{this_queue = ...contents}{const value = this_queue0this_queuereturn 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 this_queue0}// good{return this_queue0} -
9.3 Methods can return
this
to help with method chaining.// badJediprototype {thisjumping = truereturn true}Jediprototype {thisheight = height}const luke =luke // => trueluke // => undefined// good{thisjumping = truereturn this}{thisheight = heightreturn 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.
no-useless-constructor
// bad{}{return thisname}// bad{super ...args}// good{super ...argsthisname = 'Rey'}
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 migmeStyleGuide =moduleexports = migmeStyleGuidees6// okes6// 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
Iterators and Generators
-
11.1 Don't use iterators. Prefer JavaScript's higher-order functions like
map()
andreduce()
instead of loops likefor-of
. eslint:no-iterator
Why? This enforces our immutable rule. Dealing with pure functions that return values is easier to reason about than side effects.
const numbers = 1 2 3 4 5// badlet sum = 0for let num of numberssum += numsum === 15// goodlet sum = 0numberssum === 15// best (use the functional force)const sum = numberssum === 15 -
11.2 Don't use generators for now.
Why? They don't transpile well to ES5.
Properties
-
12.1 Use dot notation when accessing properties. eslint:
dot-notation
jscs:requireDotNotation
const luke =jedi: trueage: 28// badconst isJedi = luke'jedi'// goodconst isJedi = lukejedi -
12.2 Use subscript notation
[]
when accessing properties with a variable.const luke =jedi: trueage: 28{return lukeprop}const isJedi =
Variables
-
13.1 Always use
const
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.// badsuperPower =// goodconst superPower = -
13.2 Use one
const
declaration per variable. eslint:one-var
jscs:disallowMultipleVarDecl
Why? It's easier to add new variable declarations this way, and you never have to worry about adding a
,
or introducing punctuation-only diffs.// badconst items =goSportsTeam = truedragonball = 'z'// bad// (compare to above, and try to spot the mistake)const items =goSportsTeam = truedragonball = 'z'// goodconst items =const goSportsTeam = trueconst 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 iconst items =let dragonballconst goSportsTeam = truelet len// goodconst goSportsTeam = trueconst items =let dragonballlet ilet 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 falseif name === 'test'thisreturn falsereturn name}// good{if hasName === 'test'return falseconst name =if name === 'test'thisreturn falsereturn name}
Hoisting
-
14.1
var
declarations get hoisted to the top of their 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 declaredButNotAssignedconsole // => 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}}
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.
// badif name !== ''// ...stuff...// goodif name// ...stuff...// badif collectionlength > 0// ...stuff...// goodif collectionlength// ...stuff... -
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
).
Why? Lexical declarations are visible in the entire
switch
block but only get initialised when assigned, which only happens when itscase
is reached. This causes problems when multiplecase
clauses attempt to define the same thing.
eslint rules: no-case-declarations
.
```javascript
// bad
switch (foo) {
case 1:
let x = 1
break
case 2:
const y = 2
break
case 3:
function f () {}
break
default:
class C {}
}
// good
switch (foo) {
case 1: {
let x = 1
break
}
case 2: {
const y = 2
break
}
case 3: {
function f () {}
break
}
case 4:
bar()
break
default: {
class C {}
}
}
```
-
15.6 Ternaries should not be nested and generally be single line expressions.
eslint rules:
no-nested-ternary
.// badconst foo = maybe1 > maybe2? "bar": value1 > value2 ? "baz" : null// betterconst maybeNull = value1 > value2 ? 'baz' : nullconst foo = maybe1 > maybe2? 'bar': maybeNull// bestconst maybeNull = value1 > value2 ? 'baz' : nullconst foo = maybe1 > maybe2 ? 'bar' : maybeNull -
15.7 Avoid unneeded ternary statements.
eslint rules:
no-unneeded-ternary
.// badconst foo = a ? a : bconst bar = c ? true : falseconst baz = c ? false : true// goodconst foo = a || bconst bar = !!cconst baz = !c
Blocks
-
16.1 Use braces with all multi-line blocks.
// 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
jscs:disallowNewlineBeforeBlockStatements
// badif testelse// goodif testelse
-
Comments
-
17.1 Use
/** ... */
for multi-line comments. Include a description, specify types and values for all parameters and return values.// bad// make() returns a new element// based on the passed in tag name//// @param {String} tag// @return {Element} element{// ...stuff...return element}// good/*** make() returns a new element* based on the passed in tag name** @param* @return*/{// ...stuff...return element} -
17.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 = this_type || 'no type'return type}// good{console// set the default type to 'no type'const type = this_type || 'no type'return type}// also good{// set the default type to 'no type'const type = this_type || 'no type'return type} -
17.3 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
. -
17.4 Use
// FIXME:
to annotate problems.{super// FIXME: shouldn't use a global heretotal = 0} -
17.5 Use
// TODO:
to annotate solutions to problems.{super// TODO: total should be configurable by an options paramthistotal = 0}
Whitespace
-
18.1 Use soft tabs set to 2 spaces. eslint:
indent
jscs:validateIndentation
// bad{∙∙∙∙const name}// bad{∙const name}// good{∙∙const name} -
18.2 Place 1 space before the leading brace. eslint:
space-before-blocks
jscs:requireSpaceBeforeBlockStatements
// bad{console}// good{console}// baddog// gooddog -
18.3 Place 1 space before the opening parenthesis in control statements and function declarations (
if
,while
,function
, etc.). Place no space between the function name and argument list in function calls. eslint:keyword-spacing
jscs:requireSpaceAfterKeywords
// badifisJedi// goodif isJedi// bad{console}// good{console} -
18.4 Set off operators with spaces. eslint:
space-infix-ops
jscs:requireSpaceBeforeBinaryOperators
,requireSpaceAfterBinaryOperators
// badconst x=y+5// goodconst x = y + 5 -
18.5 End files with a single newline character.
// bad{// ...stuff...}this// bad{// ...stuff...}this↵↵// good{// ...stuff...}this↵ -
18.6 Use indentation when making long method chains (more than 2 method chains). Use a leading dot, which emphasises 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 -
18.7 Leave a blank line after blocks and before the next statement. jscs:
requirePaddingNewLinesAfterBlocks
// badif fooreturn barreturn baz// goodif fooreturn barreturn baz// badconst obj ={}{}return obj// goodconst obj ={}{}return obj// badconst arr ={}{}return arr// goodconst arr ={}{}return arr -
18.8 Do not pad your blocks with blank lines. eslint:
padded-blocks
jscs:disallowPaddingNewlinesInBlocks
// bad{console}// also badif bazconsoleelseconsole// good{console}// goodif bazconsoleelseconsole -
18.9 Do not add spaces inside parentheses. eslint:
space-in-parens
jscs:disallowSpacesInsideParentheses
// bad{return foo}// good{return foo}// badif fooconsole// goodif fooconsole -
18.10 Do not add spaces inside brackets. eslint:
array-bracket-spacing
jscs:disallowSpacesInsideArrayBrackets
// badconst foo = 1 2 3console// goodconst foo = 1 2 3console -
18.11 Add spaces inside curly braces. eslint:
object-curly-spacing
jscs:requireSpacesInsideObjectBrackets
// badconst foo = clark: 'kent'// goodconst foo = clark: 'kent' -
18.12 Avoid having lines of code that are longer than 100 characters (including whitespace). eslint:
max-len
jscs:maximumLineLength
Why? This ensures readability and maintainability.
// badconst foo = 'Whatever national crop flips the window. The cartoon reverts within the screw. Whatever wizard constrains a helpful ally. The counterpart ascends!'// bad$// goodconst foo = 'Whatever national crop flips the window. The cartoon reverts within the screw. ' +'Whatever wizard constrains a helpful ally. The counterpart ascends!'// good$
Commas
-
19.1 Leading commas: Nope. eslint:
comma-style
jscs:requireCommaBeforeLineBreak
// badconst story =onceuponaTime// goodconst story =onceuponaTime// badconst hero =firstName: 'Ada'lastName: 'Lovelace'birthYear: 1815superPower: 'computers'// goodconst hero =firstName: 'Ada'lastName: 'Lovelace'birthYear: 1815superPower: 'computers' -
19.2 Additional trailing comma: Yup. eslint:
comma-dangle
jscs:requireTrailingComma
Why? This leads to cleaner git diffs. Also, transpilers like Babel will remove the additional trailing comma in the transpiled code which means you don't have to worry about the trailing comma problem in legacy browsers.
// bad - git diff without trailing commaconst hero =firstName: 'Florence'- lastName: 'Nightingale'+ lastName: 'Nightingale'+ inventorOf: 'coxcomb graph' 'modern nursing'// good - git diff with trailing commaconst hero =firstName: 'Florence'lastName: 'Nightingale'+ inventorOf: 'coxcomb chart' 'modern nursing'// badconst hero =firstName: 'Dana'lastName: 'Scully'const heroes ='Batman''Superman'// goodconst hero =firstName: 'Dana'lastName: 'Scully'const heroes ='Batman''Superman'
Semicolons
-
20.1 Nope. It's fine. Really!. eslint:
semi
jscs:disallowSemicolons
// bad{const name = 'Skywalker';return name;};// good{const name = 'Skywalker'return name}// Even without semicolons, they are still allowed to disambiguate statements beginning with [, (, /, +, or -:; {const name = 'Skywalker'return name}
Type Casting & Coercion
-
21.1 Perform type coercion at the beginning of the statement.
-
21.2 Strings:
// => this.reviewScore = 9// badconst totalScore = thisreviewScore + ''// goodconst totalScore = StringthisreviewScore -
21.3 Numbers: Use
Number
for type casting andparseInt
always with a radix for parsing strings. eslint:radix
const inputValue = '4'// badconst val = inputValue// badconst val = +inputValue// badconst val = inputValue >> 0// badconst val =// goodconst val = NumberinputValue// goodconst val = -
21.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 -
21.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 -
21.6 Booleans:
const age = 0// badconst hasAge = age// goodconst hasAge = Booleanage// goodconst hasAge = !!age
Naming Conventions
-
22.1 Avoid single letter names. Be descriptive with your naming.
// bad{// ...stuff...}// good{// ..stuff..} -
22.2 Use camelCase when naming objects, functions, and instances. eslint:
camelcase
jscs:requireCamelCaseOrUpperCaseIdentifiers
// badconst OBJEcttsssss = {}const this_is_my_object = {}{}// goodconst thisIsMyObject = {}{} -
22.3 Use PascalCase when naming constructors or classes. eslint:
new-cap
jscs:requireCapitalizedConstructors
// bad{thisname = optionsname}const bad =name: 'nope'// good{thisname = optionsname}const good =name: 'yup' -
22.4 Use a leading underscore
_
when naming private properties. eslint:no-underscore-dangle
jscs:disallowDanglingUnderscores
// badthis__firstName__ = 'Panda'thisfirstName_ = 'Panda'// goodthis_firstName = 'Panda' -
22.5 Don't save references to
this
. Use arrow functions or Function#bind. jscs:disallowNodeTypes
// bad{const self = thisreturn {console}}// bad{const that = thisreturn {console}}// good{return {console}} -
22.6 If your file exports a single class, your filename should be exactly the name of the class.
// file contents// ...// in some other file// bad// bad// good -
22.7 Use camelCase when you export-default a function. Your filename should be identical to your function's name.
{} -
22.8 Use PascalCase when you export a singleton / function library / bare object.
const MigmeStyleGuide =es6:
Accessors
-
23.1 Accessor functions for properties are not required.
-
23.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() and setVal('hello').
// baddragon// gooddragon// baddragon// gooddragon -
23.3 If the property is a
boolean
, useisVal()
orhasVal()
.// badif !dragonreturn false// goodif !dragonreturn false -
23.4 It's okay to create get() and set() functions, but be consistent.
{const lightsaber = optionslightsaber || 'blue'this}thiskey = valreturn thiskey
Events
-
24.1 When attaching data payloads to events (whether DOM events or something more proprietary like Backbone events), pass 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
-
25.1 Prefix jQuery object variables with a
$
. jscs:requireDollarBeforejQueryAssignment
Why? It's a lot easier to read the code and determine which variables are assigned to jQuery objects.
// badconst sidebar =// goodconst $sidebar =// goodconst $sidebarBtn = -
25.2 Cache jQuery lookups.
// bad{// ...stuff...}// good{const $sidebar =$sidebar// ...stuff...$sidebar} -
25.3 For DOM queries use Cascading
$('.sidebar ul')
or parent > child$('.sidebar > ul')
. jsPerf -
25.4 Use
find
with scoped jQuery object queries.// bad// bad// good// good// good$sidebar
ECMAScript 5 Compatibility
- 26.1 Refer to Kangax's ES5 compatibility table.
ECMAScript 6 Styles
-
27.1 This is a collection of links to the various ES6 features.
Testing
-
28.1 Yup.
{return true} -
28.2 No, but seriously:
-
Whichever testing framework you use, you should be writing tests!
-
Strive to write many small pure functions, and minimise where mutations occur.
-
Be cautious about stubs and mocks - they can make your tests more brittle.
-
We primarily use
mocha
at migme. -
100% test coverage is a good goal to strive for, even if it's not always practical to reach it.
-
We use Codecov to help analyse our test coverage.
-
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
- Loading...
Resources
Learning ES6
- Draft ECMA 2015 (ES6) Spec
- ExploringJS
- ES6 Compatibility Table
- Comprehensive Overview of ES6 Features
Read This
Other Style Guides
- Google JavaScript Style Guide
- jQuery Core Style Guidelines
- Principles of Writing Consistent, Idiomatic JavaScript
Further Reading
- Understanding JavaScript Closures - Angus Croll
- Basic JavaScript for the impatient programmer - Dr. Axel Rauschmayer
- You Might Not Need jQuery - Zack Bloom & Adam Schwartz
- ES6 Features - Luke Hoban
- Frontend Guidelines - Benjamin De Cock
Books
- JavaScript: The Good Parts - Douglas Crockford
- JavaScript Patterns - Stoyan Stefanov
- Pro JavaScript Design Patterns - Ross Harmes and Dustin Diaz
- High Performance Web Sites: Essential Knowledge for Front-End Engineers - Steve Souders
- Maintainable JavaScript - Nicholas C. Zakas
- JavaScript Web Applications - Alex MacCaw
- Pro JavaScript Techniques - John Resig
- Smashing Node.js: JavaScript Everywhere - Guillermo Rauch
- Secrets of the JavaScript Ninja - John Resig and Bear Bibeault
- Human JavaScript - Henrik Joreteg
- Superhero.js - Kim Joar Bekkelund, Mads Mobæk, & Olav Bjorkoy
- JSBooks - Julien Bouquillon
- Third Party JavaScript - Ben Vinegar and Anton Kovalyov
- Effective JavaScript: 68 Specific Ways to Harness the Power of JavaScript - David Herman
- Eloquent JavaScript - Marijn Haverbeke
- You Don't Know JS: ES6 & Beyond - Kyle Simpson
Blogs
- DailyJS
- JavaScript Weekly
- JavaScript, JavaScript...
- Bocoup Weblog
- Adequately Good
- NCZOnline
- Perfection Kills
- Ben Alman
- Dmitry Baranovskiy
- Dustin Diaz
- nettuts
Podcasts
License
(The MIT License)
Copyright (c) 2014-2016 Airbnb
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.