Home > Tutorial > JavaScript > JavaScript Automatic Semicolon Insertion & Curly brace placement

JavaScript Automatic Semicolon Insertion & Curly brace placement

JavaScript Automatic Semicolon Insertion

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 hobbit 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.

JavaScript Automatic Semicolon Insertion
JavaScript Automatic Semicolon Insertion

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

Wait before leaving. why can’t you follow me on twitter or be a friend on Facebook or googlePlus or linkedn to get in touch me. or join our mailing list

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Arunkumar Gudelli
I am “One among a million” Software engineers of India. I write beautiful markup.I make the Web useful. You can connect me via @twitter or @facebook or Google+ or e-mail.
http://www.arungudelli.com

2 thoughts on “JavaScript Automatic Semicolon Insertion & Curly brace placement

Lets have chat