Reputation: 1569
Can anyone please explain me why foo.bar is undefined? As per my understanding,it should have printed 3. Please correct me if i am wrong.
Here is the code.
var bar = 1,
foo = {};
foo: {
bar: 2;
baz: ++bar;
};
foo.bar; //undefined
foo.baz; //undefined
bar; //2
Thanks in Advance;
Upvotes: 0
Views: 62
Reputation: 33218
You have typo is foo = {
not foo: {
. Also properties must seperate with commas ,
not semicolon:
var bar = 1,
foo = {};
foo = {
bar: 2,
baz: ++bar
};
console.log(foo.bar); //2
console.log(foo.baz); //2
console.log(bar); //2
Also please take a look Object initializer
Upvotes: 9
Reputation: 23836
Because your syntax is wrong. It should be =
assignment operator when reinitialize variable of javascript
:
var bar = 1,
foo = {};
foo = {
bar: 2,
baz: ++bar,
};
foo.bar; //2
foo.baz; //2
bar; //2
Upvotes: 0
Reputation: 207527
You are not redeclaring foo
. You are using a label.
You should have
foo = {
bar: 2,
baz: ++bar
};
Upvotes: 4