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
?