Reputation: 2579
Why does this work in JavaScript?
undefined_variable_here: 2
it returns 2 in the console
Then I tried this and it also worked
{another_undefined_variable: 3}
Is there a name or an explanation for this?
Upvotes: -1
Views: 50
Reputation: 2873
Your first example is a labeled statement: the expression "2" with the label "undefined_variable_here". Although JavaScript does not have a goto
statement, there are still a few ways to jump to specific statements under certain circumstances. In order to do that, these statements need to have some kind of identifier attached, so that the machine knows where to go, and labels provide that identifier.
Your second example is an object literal: an expression for a single object which has one property called "another_undefined_variable" with the value 3.
In both cases, semicolon insertion implicitly ends the statement. So the first example is essentially equivalent to the statement:
2;
This statement isn't very useful by itself, because it doesn't do anything, but it is legal JavaScript. The second example actually does a little bit of work, in that it has to create the object, but because it doesn't get put into a variable, there are no references left: you can't get at it, and the garbage collector will wipe it out at the next opportunity. Still not very useful, but still legal.
Upvotes: 1
Reputation: 25332
You're basically creating a label. In the second case, even if it seems to you an object, you just surrounded the label by a block statement. In short, it's like you just typed "2" in both cases for the web console.
Upvotes: 2