-1

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?

7
  • The last one is clearly legal. It simply initializes an object in JSON. Commented Mar 19, 2015 at 16:55
  • That's not true, because {a: 1, b: 2} throws an error! Commented Mar 19, 2015 at 16:58
  • 1
    @MathiasLykkegaardLorenzen it would be JSON when the identifier name was quoted. OPs code is just plain JavaScript Commented Mar 19, 2015 at 16:59
  • @LJ_1102 no, you are wrong. JSON means JavaScript Object Notation, and actually just refers to the notation used for representing objects. Sure, strings containing JSON are what JSON serializers accept, but that's not the point here. Commented Mar 19, 2015 at 17:02
  • @JadJoubran just because it didn't work in the console, doesn't mean it isn't valid JavaScript. But indeed, you did describe that it returned 2 in the console, which my code wouldn't. Commented Mar 19, 2015 at 17:06

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Thank you for the great answer! But then why adding another element would not work? Say: {a: 2, b: 3}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.