Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a for each loop on an empty array in JavaScript [duplicate]

Tags:

javascript

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.

like image 400
Craig Avatar asked Dec 11 '14 21:12

Craig


People also ask

Can you use forEach on 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.

How do you duplicate an array 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.

Are empty arrays Falsy JavaScript?

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.


2 Answers

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] 
like image 114
Faris Zacina Avatar answered Sep 22 '22 05:09

Faris Zacina


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: Screenshot from MDN regarding forEach

like image 30
Adam Avatar answered Sep 22 '22 05:09

Adam