I am having an array which contains empty elements.
let arr = ['item 1', 'item 2', , 'item 3', , 'item 4', 'item 5'];
I am trying to find out if there is any empty element in an array by using Array.some()
method but it returns false.
// Input array
const arr = ['item 1', 'item 2', , 'item 3', , 'item 4', 'item 5'];
// If you see in console, empty element has been filled with undefined
console.log(arr); // ["item 1","item 2",undefined,"item 3",undefined,"item 4","item 5"]
// Now I am just checking if is there any falsy value in an array. Ideally it should return true as we have undefined values in an arr but it is returning `false`.
console.log(arr.some(item => !item)); // false
There are so many other ways to check if is there any undefined
values in an array but here I am specifically asking about the Array.some()
behaviour. If I will explicitly replace the empty elements with undefined, then it will return true
.
const arr = ['item 1', 'item 2', undefined, 'item 3', undefined, 'item 4', 'item 5'];
console.log(arr.some(item => !item)); // true
Why is it behaving like that? Please don't provide any alternate solutions as I am aware about other alternate solutions.