function a() {
var b = ["b"];
console.log(b);
//console.log(b.slice());
b = b.push("bb");
}
a();
In a “perfect” world you would think that the console.log would show ["b"], but wildly enough it shows ["b", "bb"] even though “bb” isn’t pushed on until afterwards.
If you do console.log(b.slice()); Then you will get the desired result of ["b"]. Why is that? What’s the reason behind this complication? I just want to understand this better so I can better avoid it from happening.
* Note I hit on this same point in a recent question of mine, but this is a much more concise example. @RightSaidFred has led me to this point and has been a huge help so far.
This is a known problem with
console.log.Instead of turning the parameter into a string when you call the method, the parameter is stored and turned into a string when it’s displayed in the UI. As nothing happens in the UI while the function is running, you will see the state of the object as it is when you exit the function.