Parashuram
Parashuram

Reputation: 1569

What happens when we do the re-declaration of object in Javascript?

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

Answers (3)

Alex Char
Alex Char

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

Manwal
Manwal

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

DEMO

Upvotes: 0

epascarello
epascarello

Reputation: 207527

You are not redeclaring foo. You are using a label.

You should have

foo = {
    bar: 2,
    baz: ++bar
};

Upvotes: 4

Related Questions