ankam sarav ankam sarav - 1 year ago 82
Javascript Question

why foo: { bar: 10} prints 10 when executed in chrome console | Javascript

Being familiar with object literal after seeing the below code I guessed the last line will be "2 + 2 + 2 = 6" but when executed in chrome console, I got "Nan" as result. Initially I didn't recognize the ":" after the foo in line #4 and the semi colon next to bar in line #5 and #6. To find out why, I tried "foo: { bar: 10}" and then it printed 10. Then I came to know that the syntax is wrong but couldn't understand why it didn't throw an error and instead got an answer 10.

var bar = 1,
foo = {};

foo: {
bar: 2;
baz: ++bar;
foo.baz + + bar;

Answer Source

foo: is a label. It does nothing since it isn't labeling anything useful.

{} is a block. It groups some statements, but (in this example) not in a significant way. (Important: It is a block, not an object literal.)

bar: is another label. Ditto for foo:.

10 is a Number.

Since everything else does nothing significant, you are basically evaluating 10 so you get 10 as the result.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download