This year, before the pandemic, I was working on a personal project using newly learnt Angular framework. Now, the foremost debug tool that everyone is encouraged to use, is the print function, or the console.log(), using which we can inspect the state of variables and observe execution flow of our program or code.

Basically, I was updating an array dynamically.

Now, observe this piece of code given below:

1: A = [1,2]; 
2: console.log(A);
3: A[0] = 5;
4: console.log(A)

What should be the output?

[1, 2]
[5, 2]

Right? But, Google Chrome console outputs :

[5, 2]
[5, 2]
Console Output

Now, you wonder, how did the array change before it came across the third line? The console.log() statement is definitely above it?

Customary XKCD Comic describing your frustration!

Then, I scavenged online, till I landed on this piece of treasure on StackOverflow: https://stackoverflow.com/questions/11284663/console-log-shows-the-changed-value-of-a-variable-before-the-value-actually-ch/

Remember C pointers-and-references from your programming class?

Turns out when you code console.log(A), you actually pass a pointer or a reference to the object(here an array). And, Javascript implements a programming paradigm called “lazy evaluation” which means, it doesn’t evaluate the expression, till the need so arises.

So, you pass the pointer to console.log() and it evaluates only when you click on it, but by that time, the array has changed! Hence, it evaluates lazily and gives the final array.

Workarounds?

So how do we record the actual state of the object/array? There are various solutions:

console.log([…A]) // using the spread operator for array A
console.log(A.toString()) // convert the array to a string "[5, 2]"
console.log(json.stringify(A))

This was a damn interesting bug. Thank you for reading my story! Meet you next time!

References: XKCD Comic: https://xkcd.com/979/

This blogpost is a part of the Programming Club, IIT Kanpur blog series.

All images used here are my own images or images available online publicly.

An evergreen learner; passionate about technology😄. Currently a Sophomore at IIT Kanpur and Secy at PClub & ECell. https://www.linkedin.com/in/routsarthak/