Automatic semicolon insertion in JavaScript


In this post, I am sharing a potential issue related to automatic semicolon insertion in JavaScript.

Not that long ago I was helping one of my colleagues to investigate an issue where a method was always returning undefined value even though a literal object was used as a return value.

function calculateHash(item) {
  var hashValue

  // item hash value calculation

  return
  {
    hash: hashValue
  }
}

calculateHash(/* any item */) // -> undefined

The whole problem was caused by automatic semicolon insertion by JavaScript. ECMAScript® Language Specification describes that process in point 7.9, Automatic Semicolon Insertion.

A semicolon character is automatically inserted into the source code if a line terminator follows a ‘return’ statement. In order not to make the same mistake you should always follow this rule:

An Expression in a return or throw statement should start on the same line as the return or throw token.

JavaScript interpreted the function as follows:

function calculateHash(item) {
  // ... omitted code

  return
  {
    hash: hashValue
  }
}

The solution was straightforward - to remove the newline between return and the returned object:

function calculateHash(item) {
  var hashValue

  // item hash value calculation

  return {
    hash: hashValue
  }
}

calculateHash(/* any item */) // -> proper hash value

Tags:

#javascript #newline #semicolon


You may also be interested in:



comments powered by Disqus