Skip to content
Advertisement

Why do results vary based on curly brace placement?

Why do the code snippets below, taken from this article, produce different results due to only a single change in the placement of curly braces?

When the opening curly brace { is on a new line, test() returns undefined, and “no – it broke: undefined” is displayed in the alert.

function test()
{
  return
  { /* <--- curly brace on new line */
    javascript: "fantastic"
  };
}

var r = test();
try {
  alert(r.javascript); // does this work...?
} catch (e) {
  alert('no - it broke: ' + typeof r);
}

When the brace is on the same line as return, test() returns an object, and “fantastic” is alerted.

function test()
{
  return { /* <---- curly brace on same line */
    javascript: "fantastic"
  };
}

var r = test();
try {
  alert(r.javascript); // does this work...?
} catch (e) {
  alert('no - it broke: ' + typeof r);
}

Advertisement

Answer

That’s one of the pitfalls of JavaScript: automatic semicolon insertion. Lines that do not end with a semicolon, but could be the end of a statement, are automatically terminated, so your first example looks effectively like this:

function test()
{
  return; // <- notice the inserted semicolon
  { 
    javascript: "fantastic"
  };
}

See also Douglas Crockford’s JS style guide, which mentions semicolon insertion.

In your second example you return an object (built by the curly braces) with the property javascript and its value of "fantastic", effectively the same as this:

function test() {
    var myObject = new Object();
    myObject.javascript = "fantastic";
    return myObject;
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement