JustLearn JustLearn - 7 months ago 28
Javascript Question

Why does a results vary based on curly brace placement?

I have read this article, where an example is shown. Please explain why the code snippets below return different results due to changes in the placement of curly the braces.

Example with an opening curly brace

{
on new line.

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

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


test()
returns
undefined
.

Example with an opening curly brace
{
on same line as
return
.

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

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


test()
returns an object.

Here is live example beware of curly braces.

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 http://javascript.crockford.com/code.html

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