yaru
yaru

Reputation: 1320

Why console.log displays incorrect object's values?

I don't understand why console.log displays that d1 contains [100,200,300] before I even introduced these numbers. Regular for loop displays internals of d1 correctly though. Can someone please explain this behavior/bug of console.log in Google Chrome? https://jsfiddle.net/ZSvyt/

var container = {};
container["0"] = [10, 20, 30];
var d1 = container;

console.log('before console.log');
console.log(d1); // <--- IT DISPLAYS [100, 200, 300]. WHY?

// before for loop
console.log('before for loop');
for (var i = 0; i < d1["0"].length; i++) {
    console.log(d1["0"][i]);
}

container["0"] = [100, 200, 300];

console.log('after console.log');
console.log(d1);

// after for loop
console.log('after for loop');
for (var i = 0; i < d1["0"].length; i++) {
    console.log(d1["0"][i]);
}

Output:

before console.log
Object {
    0: Array[3]
}
0: Array[3] 
0: 100
1: 200
2: 300 

before for loop
10
20
30

after console.log
Object {
    0: Array[3]
}
0: Array[3] 
0: 100
1: 200
2: 300

after for loop
100
200
300

Upvotes: 5

Views: 3560

Answers (1)

Omar Elawady
Omar Elawady

Reputation: 3360

that's because what is in the console is the reference of dt not a copy.

you can copy the object and log it (the code from this question ).

or you can log the string that represents it using JSON.stringify.

console.log( JSON.stringify(dt) ); will print it as string.

Also if you are using lodash then you can use console.log(_.cloneDeep(dt)) to clone and log the correct values inside the object at that very moment.

Upvotes: 9

Related Questions