Output of both the arrays would be not be the same.
squared1 array - [1, 4, 9, 16]
squared2 array - [empty x 4]
When we create an array using the Array constructor providing the length of the array as argument then it returns empty slots as array elements. Function like map, forEach checks if the property/key exists on the array and then only invokes the passed callback. Hence, we will get the value of squared2
as [empty x 4]
.
To fix this, we either copy the array or use .fill
.
var nums2 = new Array(4);
nums2 = [...nums2];
or
var nums2 = new Array(4).fill(0);
For useful and amazing frontend and programming tutorials: https://bit.ly/devtools-yt