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?
Try debugging your issue in the Chrome script debugger. Put a breakpoint on the line:
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.logasynchronously. 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.