Explaining the JavaScript Quiz
According to the official JavaScript Specification, Arrays are reference type which if you are not into jargon's basically means that when you assign some variable an array value, the address of that array is stored in the variable instead of the value.
For example
let a = [1, 2, 4];let b = a;
What’s happening here is that JavaScript creates an array in the computer memory, then remembers the address where it created the array by storing that address in a
, line two takes that same address and makes another copy of that in stores in b.
let arr1 = [1, 2, 4, 5];
let arr2 = arr1;// Code Line Number 3.
arr1 = [];console.log(arr1); // -> []
console.log(arr2); // -> [1, 2, 4, 5]
Now, the interesting bit is when code line number 3 is executed, again JavaScript goes ahead and creates an array in memory and stores that address in arr1
, and indeed arr1
now points to a new array but arr2
still remembers the address of the original array address and thus reassignment doesn’t effect the value :)
But, wait I have something even better
let arr1 = [1, 2, 4, 5];
let arr2 = arr1; arr1.length = 0;console.log(arr1); // Output :- []
console.log(arr2); // Output :- []
lets talk about arr1.length = 0
, for me personally this is the hidden gem which need to be explained and this one is harder to explain.
Lets do it with the help of a fact table.
Fact Table
- Arrays in JavaScript have a length property which is not read only, meaning you can assign its value like
arr1.length = 0
. Do checkout the docs for some clever use cases. - Printing / logging things by functions like
alert
,console.log
etc works by calltoString
which return the string representation of the data, which then is directly printed / logged on the screen. This flow will look something like,
let a = [1, 2, 4, 5];step_by_step_printing(a);function step_by_step_printing(a) {
let variable_string_representation = a.toString();
alert(variable_string_representation);
}
In case of Arrays toString
works by looping over elements in regards with the length
property. Thus it becomes such that the length property controls what will you see on logging / printing in case of arrays. Isn’t that kinda interesting.
That’s it folks, you now know all the secrets of working with arrays.
Thank you for reading, hope you found it useful.
You can find more of me at Vipul Bhardwaj , DMs via Twitter at vipulbhj are open for further discussions.