Reputation: 3
The following code block should console log the array ('abc'), then enter the while loop once. In the while loop the value at the 1st index should be changed from 'a' to 'z'. Finally the array will be returned.
However, it looks like the array is changed even before entering the loop as console.log(arr) yields ["z", "b", "c"] instead of ["a", "b", "c"].
function test(str){
var arr = str.split('');
var repeat = true;
console.log(arr);
while(repeat){
repeat = false;
arr[0] = 'z';
}
return arr;
}
console.log(test('abc'));
Upvotes: 0
Views: 227
Reputation: 1074138
Some console implementations (in particular Chrome's) show you a semi-live version of the object you logged, rather than a point-in-time copy of it. Then it gets frozen depending on what you do with it in the console (and at other times too; I've never quite understood the rules, and they vary from implementation to implementation.)
Example that replicates what you're seeing for me on Chrome — run it with the console closed, then open the console to view the result:
function test(str){
var arr = str.split('');
var repeat = true;
console.log(arr);
while(repeat){
repeat = false;
arr[0] = 'z';
}
return arr;
}
console.log(test('abc'));
Run this with the console <strong>closed</strong>, then open it and look at the result.
Here's what I get when I do that, and then expand the two entries:
To be sure you're seeing a static copy instead, you could do this:
console.log(arr.join(", "));
...which logs a string containing the array entries, rather than the array object. Or you might use JSON.stringify
rather than join
. Or, for me (and your mileage may vary), having the console open when I run the first snippet above actually shows me static copies of the array (yes, really).
Example:
function test(str){
var arr = str.split('');
var repeat = true;
console.log(arr.join(", "));
while(repeat){
repeat = false;
arr[0] = 'z';
}
return arr;
}
console.log(test('abc').join(", "));
Or make a copy of the array and log the copy:
Example:
function test(str){
var arr = str.split('');
var repeat = true;
console.log(arr.slice(0));
while(repeat){
repeat = false;
arr[0] = 'z';
}
return arr;
}
console.log(test('abc').slice(0));
...but of course, if the array has objects in it, both arrays will refer to the same object, so you still might have dynamic issues.
Upvotes: 3
Reputation: 1128
As others said in chrome console.log
function works asynchronously so sometime a change to the variable after using console.log
will reflect in the log. I always print the object using
console.log(JSON.stringify(arr));
which will maintain the structure of the array or the object while printing.
Or copy the array
console.log(arr.slice(0));
Upvotes: 0