Unexpected behaviour in console.log()

In web development, I am constantly printing things to the console in order to help with debugging and pin point problems.

However today I have found a “gotcha” with console.log() that tripped me off for several hours and I couldn’t find anything on the net about it so hopefully this helps someone.

The problem is that when printing arrays to the console, it doesn’t necessarily show the live value of the array at the time of calling.
You could print an object or array to the console, and then change one of its value after printing it, and console.log() will print the changed value not the value before printing.

Here’s an example

var my_array = [111];
console.log(my_array);
my_array[1] = 222;

This prints:

[111, 222]

When I was expecting it to print:

[111]

This means that console.log() doesn’t always show the “live” representation of the real values at the time of the call.

However if I access a property on the array it will show the live values.

Example:

var my_array = [111];
console.log(my_array.length, my_array[1]);
my_array[1] = 222;

This prints as expected:

1, undefined

This is hugely annoying if you aren’t aware of this, (Or in my case I lost an entire afternoon) :)

No comments yet.

Post Comment