I've found that I can't use a for each loop on an empty array in javascript. Can anyone explain to me why this is?
I've initialized an array in javascript like so:
var arr = new Array(10);
when I use a for each loop on the array nothing happens:
arr.forEach(function(i) { i = 0; });
the result is still an array of undefined values:
arr = [ , , , , , , , , , ];
I think that maybe since each item in the array is undefined, it doesn't even execute the forEach. I would think that it would still iterate through the undefined items. Can anyone explain why this is occurring? This question is not asking how to most efficiently fill an array with zeros, it's asking details on the interaction of a for each loop and an empty array.
The forEach() loop was introduced in ES6 (ECMAScript 2015) and it executes the given function once for each element in an array in ascending order. It doesn't execute the callback function for empty array elements. You can use this method to iterate through arrays and NodeLists in JavaScript.
To duplicate an array, just return the element in your map call. numbers = [1, 2, 3]; numbersCopy = numbers. map((x) => x); If you'd like to be a bit more mathematical, (x) => x is called identity.
Values not on the list of falsy values in JavaScript are called truthy values and include the empty array [] or the empty object {} . This means almost everything evaluates to true in JavaScript — any object and almost all primitive values, everything but the falsy values.
You can use a forEach like you intended if you modify the array initialization to be:
var arr = Array.apply(null, Array(10))
And then you can do a foreach like:
arr.forEach(function(el, index) { arr[index] = 0; });
The result is:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
You're half-way right!
I think that maybe since each item in the array is undefined, it doesn't even execute the forEach.
Array.prototype.forEach does not visit indices which have been deleted or elided; this is a process called ellision. So, it executes, but skips over every element.
From MDN:
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