Permalink
Switch branches/tags
Find file Copy path
1426 lines (1003 sloc) 32.9 KB

JavaScript Standard Style

English โ€ข Espaรฑol (Latinoamรฉrica) โ€ข Italiano (Italian) โ€ข ํ•œ๊ตญ์–ด (Korean) โ€ข Portuguรชs (Brasil) โ€ข ็ฎ€ไฝ“ไธญๆ–‡ (Simplified Chinese) โ€ข ็น้ซ”ไธญๆ–‡ (Taiwanese Mandarin)

js-standard-style

This is a summary of the standard JavaScript rules.

The best way to learn about standard is to just install it and give it a try on your code.

Rules

  • Use 2 spaces for indentation.

    eslint: indent

    function hello (name) {
      console.log('hi', name)
    }
  • Use single quotes for strings except to avoid escaping.

    eslint: quotes

    console.log('hello there')
    $("<div class='box'>")
  • No unused variables.

    eslint: no-unused-vars

    function myFunction () {
      var result = something()   // โœ— avoid
    }
  • Add a space after keywords.

    eslint: keyword-spacing

    if (condition) { ... }   // โœ“ ok
    if(condition) { ... }    // โœ— avoid
  • Add a space before a function declaration's parentheses.

    eslint: space-before-function-paren

    function name (arg) { ... }   // โœ“ ok
    function name(arg) { ... }    // โœ— avoid
    
    run(function () { ... })      // โœ“ ok
    run(function() { ... })       // โœ— avoid
  • Always use === instead of ==.
    Exception: obj == null is allowed to check for null || undefined.

    eslint: eqeqeq

    if (name === 'John')   // โœ“ ok
    if (name == 'John')    // โœ— avoid
    if (name !== 'John')   // โœ“ ok
    if (name != 'John')    // โœ— avoid
  • Infix operators must be spaced.

    eslint: space-infix-ops

    // โœ“ ok
    var x = 2
    var message = 'hello, ' + name + '!'
    // โœ— avoid
    var x=2
    var message = 'hello, '+name+'!'
  • Commas should have a space after them.

    eslint: comma-spacing

    // โœ“ ok
    var list = [1, 2, 3, 4]
    function greet (name, options) { ... }
    // โœ— avoid
    var list = [1,2,3,4]
    function greet (name,options) { ... }
  • Keep else statements on the same line as their curly braces.

    eslint: brace-style

    // โœ“ ok
    if (condition) {
      // ...
    } else {
      // ...
    }
    // โœ— avoid
    if (condition) {
      // ...
    }
    else {
      // ...
    }
  • For multi-line if statements, use curly braces.

    eslint: curly

    // โœ“ ok
    if (options.quiet !== true) console.log('done')
    // โœ“ ok
    if (options.quiet !== true) {
      console.log('done')
    }
    // โœ— avoid
    if (options.quiet !== true)
      console.log('done')
  • Always handle the err function parameter.

    eslint: handle-callback-err

    // โœ“ ok
    run(function (err) {
      if (err) throw err
      window.alert('done')
    })
    // โœ— avoid
    run(function (err) {
      window.alert('done')
    })
  • Declare browser globals with a /* global */ comment.
    Exceptions are: window, document and navigator.
    Prevents accidental use of poorly-named browser globals like open, length, event, and name.

    /* global alert, prompt */
    
    alert('hi')
    prompt('ok?')

    Explicitly referencing the function or property on window is okay too, though such code will not run in a Worker which uses self instead of window.

    eslint: no-undef

    window.alert('hi')   // โœ“ ok
  • Multiple blank lines not allowed.

    eslint: no-multiple-empty-lines

    // โœ“ ok
    var value = 'hello world'
    console.log(value)
    // โœ— avoid
    var value = 'hello world'
    
    
    console.log(value)
  • For the ternary operator in a multi-line setting, place ? and : on their own lines.

    eslint: operator-linebreak

    // โœ“ ok
    var location = env.development ? 'localhost' : 'www.api.com'
    
    // โœ“ ok
    var location = env.development
      ? 'localhost'
      : 'www.api.com'
    
    // โœ— avoid
    var location = env.development ?
      'localhost' :
      'www.api.com'
  • For var declarations, write each declaration in its own statement.

    eslint: one-var

    // โœ“ ok
    var silent = true
    var verbose = true
    
    // โœ— avoid
    var silent = true, verbose = true
    
    // โœ— avoid
    var silent = true,
        verbose = true
  • Wrap conditional assignments with additional parentheses. This makes it clear that the expression is intentionally an assignment (=) rather than a typo for equality (===).

    eslint: no-cond-assign

    // โœ“ ok
    while ((m = text.match(expr))) {
      // ...
    }
    
    // โœ— avoid
    while (m = text.match(expr)) {
      // ...
    }
  • Add spaces inside single line blocks.

    eslint: block-spacing

      function foo () {return true}    // โœ— avoid
      function foo () { return true }  // โœ“ ok
  • Use camelcase when naming variables and functions.

    eslint: camelcase

      function my_function () { }    // โœ— avoid
      function myFunction () { }     // โœ“ ok
    
      var my_var = 'hello'           // โœ— avoid
      var myVar = 'hello'            // โœ“ ok
  • Trailing commas not allowed.

    eslint: comma-dangle

      var obj = {
        message: 'hello',   // โœ— avoid
      }
  • Commas must be placed at the end of the current line.

    eslint: comma-style

      var obj = {
        foo: 'foo'
        ,bar: 'bar'   // โœ— avoid
      }
    
      var obj = {
        foo: 'foo',
        bar: 'bar'   // โœ“ ok
      }
  • Dot should be on the same line as property.

    eslint: dot-location

      console.
        log('hello')  // โœ— avoid
    
      console
        .log('hello') // โœ“ ok
  • Files must end with a newline.

    eslint: eol-last

  • No space between function identifiers and their invocations.

    eslint: func-call-spacing

    console.log ('hello') // โœ— avoid
    console.log('hello')  // โœ“ ok
  • Add space between colon and value in key value pairs.

    eslint: key-spacing

    var obj = { 'key' : 'value' }    // โœ— avoid
    var obj = { 'key' :'value' }     // โœ— avoid
    var obj = { 'key':'value' }      // โœ— avoid
    var obj = { 'key': 'value' }     // โœ“ ok
  • Constructor names must begin with a capital letter.

    eslint: new-cap

    function animal () {}
    var dog = new animal()    // โœ— avoid
    
    function Animal () {}
    var dog = new Animal()    // โœ“ ok
  • Constructor with no arguments must be invoked with parentheses.

    eslint: new-parens

    function Animal () {}
    var dog = new Animal    // โœ— avoid
    var dog = new Animal()  // โœ“ ok
  • Objects must contain a getter when a setter is defined.

    eslint: accessor-pairs

    var person = {
      set name (value) {    // โœ— avoid
        this._name = value
      }
    }
    
    var person = {
      set name (value) {
        this._name = value
      },
      get name () {         // โœ“ ok
        return this._name
      }
    }
  • Constructors of derived classes must call super.

    eslint: constructor-super

    class Dog {
      constructor () {
        super()   // โœ— avoid
      }
    }
    
    class Dog extends Mammal {
      constructor () {
        super()   // โœ“ ok
      }
    }
  • Use array literals instead of array constructors.

    eslint: no-array-constructor

    var nums = new Array(1, 2, 3)   // โœ— avoid
    var nums = [1, 2, 3]            // โœ“ ok
  • Avoid using arguments.callee and arguments.caller.

    eslint: no-caller

    function foo (n) {
      if (n <= 0) return
    
      arguments.callee(n - 1)   // โœ— avoid
    }
    
    function foo (n) {
      if (n <= 0) return
    
      foo(n - 1)
    }
  • Avoid modifying variables of class declarations.

    eslint: no-class-assign

    class Dog {}
    Dog = 'Fido'    // โœ— avoid
  • Avoid modifying variables declared using const.

    eslint: no-const-assign

    const score = 100
    score = 125       // โœ— avoid
  • Avoid using constant expressions in conditions (except loops).

    eslint: no-constant-condition

    if (false) {    // โœ— avoid
      // ...
    }
    
    if (x === 0) {  // โœ“ ok
      // ...
    }
    
    while (true) {  // โœ“ ok
      // ...
    }
  • No control characters in regular expressions.

    eslint: no-control-regex

    var pattern = /\x1f/    // โœ— avoid
    var pattern = /\x20/    // โœ“ ok
  • No debugger statements.

    eslint: no-debugger

    function sum (a, b) {
      debugger      // โœ— avoid
      return a + b
    }
  • No delete operator on variables.

    eslint: no-delete-var

    var name
    delete name     // โœ— avoid
  • No duplicate arguments in function definitions.

    eslint: no-dupe-args

    function sum (a, b, a) {  // โœ— avoid
      // ...
    }
    
    function sum (a, b, c) {  // โœ“ ok
      // ...
    }
  • No duplicate name in class members.

    eslint: no-dupe-class-members

    class Dog {
      bark () {}
      bark () {}    // โœ— avoid
    }
  • No duplicate keys in object literals.

    eslint: no-dupe-keys

    var user = {
      name: 'Jane Doe',
      name: 'John Doe'    // โœ— avoid
    }
  • No duplicate case labels in switch statements.

    eslint: no-duplicate-case

    switch (id) {
      case 1:
        // ...
      case 1:     // โœ— avoid
    }
  • Use a single import statement per module.

    eslint: no-duplicate-imports

    import { myFunc1 } from 'module'
    import { myFunc2 } from 'module'          // โœ— avoid
    
    import { myFunc1, myFunc2 } from 'module' // โœ“ ok
  • No empty character classes in regular expressions.

    eslint: no-empty-character-class

    const myRegex = /^abc[]/      // โœ— avoid
    const myRegex = /^abc[a-z]/   // โœ“ ok
  • No empty destructuring patterns.

    eslint: no-empty-pattern

    const { a: {} } = foo         // โœ— avoid
    const { a: { b } } = foo      // โœ“ ok
  • No using eval().

    eslint: no-eval

    eval( "var result = user." + propName ) // โœ— avoid
    var result = user[propName]             // โœ“ ok
  • No reassigning exceptions in catch clauses.

    eslint: no-ex-assign

    try {
      // ...
    } catch (e) {
      e = 'new value'             // โœ— avoid
    }
    
    try {
      // ...
    } catch (e) {
      const newVal = 'new value'  // โœ“ ok
    }
  • No extending native objects.

    eslint: no-extend-native

    Object.prototype.age = 21     // โœ— avoid
  • Avoid unnecessary function binding.

    eslint: no-extra-bind

    const name = function () {
      getName()
    }.bind(user)    // โœ— avoid
    
    const name = function () {
      this.getName()
    }.bind(user)    // โœ“ ok
  • Avoid unnecessary boolean casts.

    eslint: no-extra-boolean-cast

    const result = true
    if (!!result) {   // โœ— avoid
      // ...
    }
    
    const result = true
    if (result) {     // โœ“ ok
      // ...
    }
  • No unnecessary parentheses around function expressions.

    eslint: no-extra-parens

    const myFunc = (function () { })   // โœ— avoid
    const myFunc = function () { }     // โœ“ ok
  • Use break to prevent fallthrough in switch cases.

    eslint: no-fallthrough

    switch (filter) {
      case 1:
        doSomething()    // โœ— avoid
      case 2:
        doSomethingElse()
    }
    
    switch (filter) {
      case 1:
        doSomething()
        break           // โœ“ ok
      case 2:
        doSomethingElse()
    }
    
    switch (filter) {
      case 1:
        doSomething()
        // fallthrough  // โœ“ ok
      case 2:
        doSomethingElse()
    }
  • No floating decimals.

    eslint: no-floating-decimal

    const discount = .5      // โœ— avoid
    const discount = 0.5     // โœ“ ok
  • Avoid reassigning function declarations.

    eslint: no-func-assign

    function myFunc () { }
    myFunc = myOtherFunc    // โœ— avoid
  • No reassigning read-only global variables.

    eslint: no-global-assign

    window = {}     // โœ— avoid
  • No implied eval().

    eslint: no-implied-eval

    setTimeout("alert('Hello world')")                   // โœ— avoid
    setTimeout(function () { alert('Hello world') })     // โœ“ ok
  • No function declarations in nested blocks.

    eslint: no-inner-declarations

    if (authenticated) {
      function setAuthUser () {}    // โœ— avoid
    }
  • No invalid regular expression strings in RegExp constructors.

    eslint: no-invalid-regexp

    RegExp('[a-z')    // โœ— avoid
    RegExp('[a-z]')   // โœ“ ok
  • No irregular whitespace.

    eslint: no-irregular-whitespace

    function myFunc () /*<NBSP>*/{}   // โœ— avoid
  • No using __iterator__.

    eslint: no-iterator

    Foo.prototype.__iterator__ = function () {}   // โœ— avoid
  • No labels that share a name with an in scope variable.

    eslint: no-label-var

    var score = 100
    function game () {
      score: while (true) {      // โœ— avoid
        score -= 10
        if (score > 0) continue score
        break
      }
    }
  • No label statements.

    eslint: no-labels

    label:
      while (true) {
        break label     // โœ— avoid
      }
  • No unnecessary nested blocks.

    eslint: no-lone-blocks

    function myFunc () {
      {                   // โœ— avoid
        myOtherFunc()
      }
    }
    
    function myFunc () {
      myOtherFunc()       // โœ“ ok
    }
  • Avoid mixing spaces and tabs for indentation.

    eslint: no-mixed-spaces-and-tabs

  • Do not use multiple spaces except for indentation.

    eslint: no-multi-spaces

    const id =    1234    // โœ— avoid
    const id = 1234       // โœ“ ok
  • No multiline strings.

    eslint: no-multi-str

    const message = 'Hello \
                     world'     // โœ— avoid
  • No new without assigning object to a variable.

    eslint: no-new

    new Character()                     // โœ— avoid
    const character = new Character()   // โœ“ ok
  • No using the Function constructor.

    eslint: no-new-func

    var sum = new Function('a', 'b', 'return a + b')    // โœ— avoid
  • No using the Object constructor.

    eslint: no-new-object

    let config = new Object()   // โœ— avoid
  • No using new require.

    eslint: no-new-require

    const myModule = new require('my-module')    // โœ— avoid
  • No using the Symbol constructor.

    eslint: no-new-symbol

    const foo = new Symbol('foo')   // โœ— avoid
  • No using primitive wrapper instances.

    eslint: no-new-wrappers

    const message = new String('hello')   // โœ— avoid
  • No calling global object properties as functions.

    eslint: no-obj-calls

    const math = Math()   // โœ— avoid
  • No octal literals.

    eslint: no-octal

    const num = 042     // โœ— avoid
    const num = '042'   // โœ“ ok
  • No octal escape sequences in string literals.

    eslint: no-octal-escape

    const copyright = 'Copyright \251'  // โœ— avoid
  • Avoid string concatenation when using __dirname and __filename.

    eslint: no-path-concat

    const pathToFile = __dirname + '/app.js'            // โœ— avoid
    const pathToFile = path.join(__dirname, 'app.js')   // โœ“ ok
  • Avoid using __proto__. Use getPrototypeOf instead.

    eslint: no-proto

    const foo = obj.__proto__               // โœ— avoid
    const foo = Object.getPrototypeOf(obj)  // โœ“ ok
  • No redeclaring variables.

    eslint: no-redeclare

    let name = 'John'
    let name = 'Jane'     // โœ— avoid
    
    let name = 'John'
    name = 'Jane'         // โœ“ ok
  • Avoid multiple spaces in regular expression literals.

    eslint: no-regex-spaces

    const regexp = /test   value/   // โœ— avoid
    
    const regexp = /test {3}value/  // โœ“ ok
    const regexp = /test value/     // โœ“ ok
  • Assignments in return statements must be surrounded by parentheses.

    eslint: no-return-assign

    function sum (a, b) {
      return result = a + b     // โœ— avoid
    }
    
    function sum (a, b) {
      return (result = a + b)   // โœ“ ok
    }
  • Avoid assigning a variable to itself

    eslint: no-self-assign

    name = name   // โœ— avoid
  • Avoid comparing a variable to itself.

    eslint: no-self-compare

    if (score === score) {}   // โœ— avoid
  • Avoid using the comma operator.

    eslint: no-sequences

    if (doSomething(), !!test) {}   // โœ— avoid
  • Restricted names should not be shadowed.

    eslint: no-shadow-restricted-names

    let undefined = 'value'     // โœ— avoid
  • Sparse arrays are not allowed.

    eslint: no-sparse-arrays

    let fruits = ['apple',, 'orange']       // โœ— avoid
  • Tabs should not be used

    eslint: no-tabs

  • Regular strings must not contain template literal placeholders.

    eslint: no-template-curly-in-string

    const message = 'Hello ${name}'   // โœ— avoid
    const message = `Hello ${name}`   // โœ“ ok
  • super() must be called before using this.

    eslint: no-this-before-super

    class Dog extends Animal {
      constructor () {
        this.legs = 4     // โœ— avoid
        super()
      }
    }
  • Only throw an Error object.

    eslint: no-throw-literal

    throw 'error'               // โœ— avoid
    throw new Error('error')    // โœ“ ok
  • Whitespace not allowed at end of line.

    eslint: no-trailing-spaces

  • Initializing to undefined is not allowed.

    eslint: no-undef-init

    let name = undefined    // โœ— avoid
    
    let name
    name = 'value'          // โœ“ ok
  • No unmodified conditions of loops.

    eslint: no-unmodified-loop-condition

    for (let i = 0; i < items.length; j++) {...}    // โœ— avoid
    for (let i = 0; i < items.length; i++) {...}    // โœ“ ok
  • No ternary operators when simpler alternatives exist.

    eslint: no-unneeded-ternary

    let score = val ? val : 0     // โœ— avoid
    let score = val || 0          // โœ“ ok
  • No unreachable code after return, throw, continue, and break statements.

    eslint: no-unreachable

    function doSomething () {
      return true
      console.log('never called')     // โœ— avoid
    }
  • No flow control statements in finally blocks.

    eslint: no-unsafe-finally

    try {
      // ...
    } catch (e) {
      // ...
    } finally {
      return 42     // โœ— avoid
    }
  • The left operand of relational operators must not be negated.

    eslint: no-unsafe-negation

    if (!key in obj) {}       // โœ— avoid
    if (!(key in obj)) {}     // โœ“ ok
  • Avoid unnecessary use of .call() and .apply().

    eslint: no-useless-call

    sum.call(null, 1, 2, 3)   // โœ— avoid
  • Avoid using unnecessary computed property keys on objects.

    eslint: no-useless-computed-key

    const user = { ['name']: 'John Doe' }   // โœ— avoid
    const user = { name: 'John Doe' }       // โœ“ ok
  • No unnecessary constructor.

    eslint: no-useless-constructor

    class Car {
      constructor () {      // โœ— avoid
      }
    }
  • No unnecessary use of escape.

    eslint: no-useless-escape

    let message = 'Hell\o'  // โœ— avoid
  • Renaming import, export, and destructured assignments to the same name is not allowed.

    eslint: no-useless-rename

    import { config as config } from './config'     // โœ— avoid
    import { config } from './config'               // โœ“ ok
  • No whitespace before properties.

    eslint: no-whitespace-before-property

    user .name      // โœ— avoid
    user.name       // โœ“ ok
  • No using with statements.

    eslint: no-with

    with (val) {...}    // โœ— avoid
  • Maintain consistency of newlines between object properties.

    eslint: object-property-newline

    const user = {
      name: 'Jane Doe', age: 30,
      username: 'jdoe86'            // โœ— avoid
    }
    
    const user = { name: 'Jane Doe', age: 30, username: 'jdoe86' }    // โœ“ ok
    
    const user = {
      name: 'Jane Doe',
      age: 30,
      username: 'jdoe86'
    }                                                                 // โœ“ ok
  • No padding within blocks.

    eslint: padded-blocks

    if (user) {
                                // โœ— avoid
      const name = getName()
    
    }
    
    if (user) {
      const name = getName()    // โœ“ ok
    }
  • No whitespace between spread operators and their expressions.

    eslint: rest-spread-spacing

    fn(... args)    // โœ— avoid
    fn(...args)     // โœ“ ok
  • Semicolons must have a space after and no space before.

    eslint: semi-spacing

    for (let i = 0 ;i < items.length ;i++) {...}    // โœ— avoid
    for (let i = 0; i < items.length; i++) {...}    // โœ“ ok
  • Must have a space before blocks.

    eslint: space-before-blocks

    if (admin){...}     // โœ— avoid
    if (admin) {...}    // โœ“ ok
  • No spaces inside parentheses.

    eslint: space-in-parens

    getName( name )     // โœ— avoid
    getName(name)       // โœ“ ok
  • Unary operators must have a space after.

    eslint: space-unary-ops

    typeof!admin        // โœ— avoid
    typeof !admin        // โœ“ ok
  • Use spaces inside comments.

    eslint: spaced-comment

    //comment           // โœ— avoid
    // comment          // โœ“ ok
    
    /*comment*/         // โœ— avoid
    /* comment */       // โœ“ ok
  • No spacing in template strings.

    eslint: template-curly-spacing

    const message = `Hello, ${ name }`    // โœ— avoid
    const message = `Hello, ${name}`      // โœ“ ok
  • Use isNaN() when checking for NaN.

    eslint: use-isnan

    if (price === NaN) { }      // โœ— avoid
    if (isNaN(price)) { }       // โœ“ ok
  • typeof must be compared to a valid string.

    eslint: valid-typeof

    typeof name === 'undefimed'     // โœ— avoid
    typeof name === 'undefined'     // โœ“ ok
  • Immediately Invoked Function Expressions (IIFEs) must be wrapped.

    eslint: wrap-iife

    const getName = function () { }()     // โœ— avoid
    
    const getName = (function () { }())   // โœ“ ok
    const getName = (function () { })()   // โœ“ ok
  • The * in yield*expressions must have a space before and after.

    eslint: yield-star-spacing

    yield* increment()    // โœ— avoid
    yield * increment()   // โœ“ ok
  • Avoid Yoda conditions.

    eslint: yoda

    if (42 === age) { }    // โœ— avoid
    if (age === 42) { }    // โœ“ ok

Semicolons

  • No semicolons. (see: 1, 2, 3)

    eslint: semi

    window.alert('hi')   // โœ“ ok
    window.alert('hi');  // โœ— avoid
  • Never start a line with (, [, `, or a handful of other unlikely possibilities.

    This is the only gotcha with omitting semicolons, and standard protects you from this potential issue.

    (The full list is: [, (, `, +, *, /, -, ,, ., but most of these will never appear at the start of a line in real code.)

    eslint: no-unexpected-multiline

    // โœ“ ok
    ;(function () {
      window.alert('ok')
    }())
    
    // โœ— avoid
    (function () {
      window.alert('ok')
    }())
    // โœ“ ok
    ;[1, 2, 3].forEach(bar)
    
    // โœ— avoid
    [1, 2, 3].forEach(bar)
    // โœ“ ok
    ;`hello`.indexOf('o')
    
    // โœ— avoid
    `hello`.indexOf('o')

    Note: If you're often writing code like this, you may be trying to be too clever.

    Clever short-hands are discouraged, in favor of clear and readable expressions, whenever possible.

    Instead of this:

    ;[1, 2, 3].forEach(bar)

    This is strongly preferred:

    var nums = [1, 2, 3]
    nums.forEach(bar)

Helpful reading

And a helpful video:

All popular code minifiers in use today use AST-based minification, so they can handle semicolon-less JavaScript with no issues (since semicolons are not required in JavaScript).

Excerpt from "An Open Letter to JavaScript Leaders Regarding Semicolons":

[Relying on automatic semicolon insertion] is quite safe, and perfectly valid JS that every browser understands. Closure compiler, yuicompressor, packer, and jsmin all can properly minify it. There is no performance impact anywhere.

I am sorry that, instead of educating you, the leaders in this language community have given you lies and fear. That was shameful. I recommend learning how statements in JS are actually terminated (and in which cases they are not terminated), so that you can write code that you find beautiful.

In general, \n ends a statement unless:

  1. The statement has an unclosed paren, array literal, or object literal or ends in some other way that is not a valid way to end a statement. (For instance, ending with . or ,.)
  2. The line is -- or ++ (in which case it will decrement/increment the next token.)
  3. It is a for(), while(), do, if(), or else, and there is no {
  4. The next line starts with [, (, +, *, /, -, ,, ., or some other binary operator that can only be found between two tokens in a single expression.

The first is pretty obvious. Even JSLint is ok with \n chars in JSON and parenthesized constructs, and with var statements that span multiple lines ending in ,.

The second is super weird. Iโ€™ve never seen a case (outside of these sorts of conversations) where youโ€™d want to do write i\n++\nj, but, point of fact, thatโ€™s parsed as i; ++j, not i++; j.

The third is well understood, if generally despised. if (x)\ny() is equivalent to if (x) { y() }. The construct doesnโ€™t end until it reaches either a block, or a statement.

; is a valid JavaScript statement, so if(x); is equivalent to if(x){} or, โ€œIf x, do nothing.โ€ This is more commonly applied to loops where the loop check also is the update function. Unusual, but not unheard of.

The fourth is generally the fud-inducing โ€œoh noes, you need semicolons!โ€ case. But, as it turns out, itโ€™s quite easy to prefix those lines with semicolons if you donโ€™t mean them to be continuations of the previous line. For example, instead of this:

foo();
[1,2,3].forEach(bar);

you could do this:

foo()
;[1,2,3].forEach(bar)

The advantage is that the prefixes are easier to notice, once you are accustomed to never seeing lines starting with ( or [ without semis.