JavaScript console prints assigned value of variable before it has been assigned?

I'm deeply confused by the behaviour of either JavaScript, or the Chrome console. Can someone help me understand?

Basically I have the following JavaScript code, not nested inside any function or other scope:

var initial_array = [];

function initialiseArray() { 
   initial_array = [2, 9, 8, 6, 0, 2, 1];
} 

function copyToNewArray() {
    var copied_array = [];

    console.log("COPIED 1", copied_array);

    for (var i = 0; i < initial_array.length; i++) {
        var copy = initial_array[i];
        copied_array.push(copy);
    }

    console.log("COPIED 2", copied_array);
}

initialiseArray();
copyToNewArray();

I would expect COPIED 1 to print [] - as the variable hasn't been assigned yet - but instead it prints [2, 9, 8, 6, 0, 2, 1] - ie the value after it has been assigned.

Why?

Incidentally, if you replace lines 8-11 with initial_array = copied_array, then RESULTS 1 does indeed print as []. Is it something to do with using .push?

Answers:

Answer

Try debugging your issue in the Chrome script debugger. Put a breakpoint on the line:

for (var i = 0; i < initial_array.length; i++) {

and you will see the behaviour you desire.

The problem you are having is you are making the incorrect assumption that the Chrome debugger 'prints' the value immediately when in fact it does the console.log asynchronously. Since arrays are passed around by reference in the backend when it actually goes to print the value it is now the one you are seeing.

Answer

Since arrays are passed by reference, every change you make to it will change what is output in the console. It is partly the behavior of Chrome's console, partly JavaScript's.

If you want to print the result at the time of the call to console.log, you could output it as a string using JSON.stringify.

console.log("COPIED 1", JSON.stringify(copied_array));

Important edit

It seems I was mostly wrong. As diEcho pointed out in the question's comments, a similar question has a better answer. It seems to be solely Chrome behavior.

Answer

The console is actually asynchronous. Because you're logging a reference to an object, by the time the object is logged it has already changed.

You could clone the array before logging it to be certain that it doesn't get changed before it gets logged.

Answer

It's the way arrays are displayed in the Chrome console, and that's by reference. If you want accurate results, convert to a string:

var initial_array = [];

function initialiseArray() { 
   initial_array = [2, 9, 8, 6, 0, 2, 1];
} 

function copyToNewArray() {
    var copied_array = [];

    console.log("COPIED 1", copied_array.toString());

    for (var i = 0; i < initial_array.length; i++) {
        var copy = initial_array[i];
        copied_array.push(copy);
    }

    console.log("COPIED 2", copied_array.toString());
}

initialiseArray();
copyToNewArray();

You can test this out pretty easily:

var x = [];
console.log(x), x.push(5), x; // outputs [5] and [5]
Answer
var initial_array = [];
 function initialiseArray() { 
   initial_array = [2, 9, 8, 6, 0, 2, 1];
} 
function copyToNewArray() {
    var copied_array = [];
    console.log("COPIED 1", copied_array);
    alert(copied_array.length);
    for (var i = 0; i < initial_array.length; i++) {
        var copy = initial_array[i];
        copied_array.push(copy);
    }
    console.log("COPIED 2", copied_array);
}
initialiseArray();
copyToNewArray();

Adding the line alert(copied_array.length); will show correct results.

What happens is that the log is not synchronized with the javascript execution. When the log prints the values were already changed.

Answer

that's because the copied_array is a reference, and console.log is executed asynchonously, so the content of the array is modifed before the first log prints it.

you may copy the array before printing

console.log([].concat(copied_array));
Answer

If you want to keep the console's functionality such as expanding objects in an array, I suggest using .slice, which makes a copy of the array which doesn't change when logging:

console.log("COPIED 1", copied_array.slice());

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.