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
?
If you want to do this to an object that has been already logged (one time thing), chrome console offers a good solution. Hover over the printed object in the console, right click, then click on "Store as Global Variable". Chrome will assign it to a temporary var name for you which you can use in the console.
JavaScript Print JavaScript does not have any print object or print methods. You cannot access output devices from JavaScript. The only exception is that you can call the window.print() method in the browser to print the content of the current window.
Assignment (=) The simple assignment operator ( = ) is used to assign a value to a variable. The assignment operation evaluates to the assigned value. Chaining the assignment operator is possible in order to assign a single value to multiple variables.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With