Semicolons matter

js-semicolon

When your code’s intention is ambiguous, your JavaScript engine will attempt to fill in the gaps. If there are multiple potential intentions, your engine will tend to assume you meant to do the right thing. Multi-line statements are supported, omitting semicolons is not, and therefore if the case is ambiguous your engine will assume you meant to write a multi-line statement.

Take the following example:

function Logger() { }

// Log something to the console at a specified level
Logger.prototype.log = function(level) {
  console[level || 'log'].apply(console, [].slice.apply(arguments, 1));
}

// Sugar functions for Logger.log
['info', 'warn', 'error'].forEach(function(level) {
  Logger.prototype[level] = function () {
    return this.log.apply(this, [level].concat(Array.from(arguments)));
  }
});

What will happen when this is run? Did you spot the missing semicolons? Here’s a summary of how v8 sees it (I’ve removed the internals for clarity):

Logger.prototype.log = 
  function() { }['info', 'warn', 'error'].forEach(function() { });

Which is perfectly valid code; it is the rough equivalent of:

function foo() { }
Logger.prototype.log = foo['error'].forEach(function() { });

Be unambiguous with your code. If you’re ending a statement, use a semicolon.