Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does console.log output modified values even before they have been modified? [duplicate]

In Chrome 39 developer tools, this code:

var something = [
    {x: 'foo'},
    {x: 'foo'}
];

console.log(something);

something.forEach(function (element) {
    element['x'] = 'baz';
});

... outputs:

enter image description here

Why does console.log output modified values even before they have been modified?

A similar question from 2012 explains that due to a chromium bug, console.log is "delayed" (does not stringify the input object immediately). But the bug is marked as fixed, so why is this still happening several years later?

like image 756
mtmacdonald Avatar asked Oct 19 '25 19:10

mtmacdonald


1 Answers

It doesn't.

When you output an object with console.log, the object is output "by reference"; the values in the console are dynamic, and they will update to reflect the current state of the object.

If you want to output a static string of text about the object, use console.dir

like image 65
meagar Avatar answered Oct 22 '25 07:10

meagar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!