Littlee
Littlee

Reputation: 4327

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

Upvotes: 3

Views: 449

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074465

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

Upvotes: 5

Robby Cornelissen
Robby Cornelissen

Reputation: 97152

Most array operations don't operate on unassigned indexes in sparse arrays. From the MDN documentation:

callback is invoked only for array indexes which have assigned values. It is not invoked for indexes which have been deleted, or which have never been assigned values.

You only have one index with an assigned value which is truthy, so your call to every() will return true.

Upvotes: 1

Related Questions