views:

133

answers:

2

In Firefox console, this code will generate error:

{"d" : ["bankaccountnumber", "$1234.56"] } 
>   SyntaxError: invalid label {
> message="invalid label",  more...}

this code works just fine

{d : ["bankaccountnumber", "$1234.56"] } 
> ["bankaccountnumber", "$1234.56"]

this code works fine as well

var a = {'d' : ["bankaccountnumber", "$1234.56"] };
a.d
> ["bankaccountnumber", "$1234.56"]

Can someone help to explain why is the diference? thanks!

+5  A: 

This is because of ambiguous syntax. When you try to make a plain object literal in the first two lines, JavaScript is really interpreting it as a set of braces, then a label, then a statement:

{
    d: ["bankaccountnumber", "$1234.56"]
}

This code doesn't evaluate to an object, but just to the array. The first example, you tried to use a string as a label, which is in correct syntax. The third example works properly, creating an object and storing it in a.

Claudiu
+1 @OP: In order for it to be an expression (an object literal) rather than braces around a label followed by an array literal, you have to use it as a right-hand value (as in your last example). As right-hand values, all three of those would have been valid object literal notation (the one using `d:`, the one using `"d":`, and the one using `'d':`). Somewhat OT, but only the `"d":` one would be valid JSON, if that's relevant to what you're doing, because JSON is a *subset* of object literal notation. (http://json.org)
T.J. Crowder
Why, oh why, did they put GOTOs in Javascript... *sigh*
Matt Ball
@Bears: They didn't, Javascript doesn't have `goto` statements. It does have labels, which are useful for `break`ing out of inner loops and such. (See section 12.12 of the 5th edition specification. In earlier specs, `goto` was a reserved symbol but there was no `goto` statement -- e.g., they were hedging their bets. As of 5th edition, no more hedging.)
T.J. Crowder
@Claudi: Why does the second example works also?
OscarRyz
@Oscar: The 2nd example doesn't work. It doesn't produce an object literal. It just happens to be valid syntax for evaluating a block with a label and an array expression
Claudiu
+3  A: 

it is probably having a hard time deciding whether it is an expression or a block. If you use parenthesis around the object it works as it forces an expression. The grouping operator, ( and ), forces { and } to be parsed as object literal.

({"d" : ["bankaccountnumber", "$1234.56"] }) // works

Read Named function expressions demystified. Its not directly related to this issue but does address it when talking about the use of grouping-parenthesis and eval().

David Murdoch