Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.prototype.every return true when testing empty value in an array has length?

I am trying to check is every element is array has truthy value.

But I am confused when testing an array has some empty value.

var arr = [];
arr[10] = 1;
arr; // [empty x 10, 1];
arr.every(item => Boolean(item)); // true ???
Boolean(arr[0]); // false ???!!!

this is what I get when running the code above on chrome devtool console enter image description here

like image 701
Littlee Avatar asked Feb 16 '26 23:02

Littlee


1 Answers

every, some, map, filter, and most of the others only visit array entries that exist, they don't visit the gaps in sparse arrays like yours. So the result is only based on checking the values of elements that actually exist.

You can see that if you step through the callback or add logging to it:

var arr = [];
arr[10] = 1;
arr.every((item, index) => {
    console.log(`Visited index ${index}, item = ${item}`);
    return Boolean(item);
});
// =>
// Visited index 10, item = 1


// Note that 0-9 are gaps:
console.log(`0 in arr? ${0 in arr}`);   // false
console.log(`9 in arr? ${9 in arr}`);   // false
console.log(`10 in arr? ${10 in arr}`); // true

As you can see, the every callback in that only outputs one line because it's only called once.

If you want that array to actually have undefined for elements 0 through 9, you could use fill; then every would test element 0 and return false since Boolean(undefined) is false:

var index = 10;
var arr = Array(index + 1).fill();
arr[index] = 1;
console.log(arr.every(Boolean)); // false
like image 103
T.J. Crowder Avatar answered Feb 19 '26 12:02

T.J. Crowder