JavaScript Automatic Semicolon Insertion & Curly Brace Placement

JavaScript is tricky sometimes & every time it offers something new to learn.

Have a look at the following JavaScript example

function foo1()
{
  return
  {
    text: "hello"
  };
}

function foo2()
{
  return{
    text: "hello"
  };
}
console.log(foo1());
console.log(foo2());

 

Both functions seem to be same and if you are a beginner in JavaScript you would expect both console logs display the same result.

undefined
{ text: 'hello' }

foo1() displays undefined. Whats wrong with the code? If you see the foo1() method definition, after return statement curly brace starts from the new line. Whats wrong with it.

In JavaScript semicolons are optional. If you are coming from traditional programming languages you have a habit of inserting semicolons after each statement. But most of the JavaScript developers ignore semicolons as they are not necessary.

But in background automatic semicolon insertion being done by JavaScript interpreters based on few rules.

That is the problem with the above code.

Because of JavaScript Automatic Semicolon insertion. The above code interpreted as

function foo1()
{
  return ;   // Semicolon being inserted by javascript interpreters 
  {
    text: "hello"
  };
}

So because of semicolon after return statement function, execution stops there and return undefined. ignoring the below code block.

One workaround will be using the code block in foo2() or

function foo1() 
{
  var obj =
  {
    text: "hello"
  };
  return obj;
}

But this is not required as long as you know the basics of JavaScript and use semicolon whenever you think it is necessary to increase readability. Be careful while using return statement with curly braces.

Reference: Rules of Automatic Semicolon Insertion