Why do results vary based on curly brace placement?

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;
}

Leave a Comment