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];
3: A = 5;
What should be the output?
Right? But, Google Chrome console outputs :
Now, you wonder, how did the array change before it came across the third line? The console.log() statement is definitely above it?
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?
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.
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]"
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.