Difference between JavaScript Array every and some - Stack Overflow
What is the correct situation to use array.find() vs. array.includes vs. array.some() ?
Javascript array.some() function does not work as it should? - Stack Overflow
javascript - Why Array.some() method behaving differently? - Stack Overflow
Videos
(If you know C# LINQ , it's like Any vs All)
somewill return true if any predicate istrueeverywill return true if all predicate istrue
Where predicate means function that returns bool ( true/false) for each element
every returns on first false.
some returns on first true
some is analogue to logical or
every is analogue to logical and
logically every implies some, but not in reverse
try this:
var identity = function(x){return x}
console.log([true, true].some(identity))//true
console.log([true, true].every(identity))//true
console.log([true, false].some(identity))//true
console.log([true, false].every(identity))//false
console.log([false, false].some(identity))//false
console.log([false, false].every(identity))//false
console.log([undefined, true].some(identity))//true
console.log([undefined, true].every(identity))//false
console.log([undefined, false].some(identity))//false
console.log([undefined, false].every(identity))//false
console.log([undefined, undefined].some(identity))//false
console.log([undefined, undefined].every(identity))//false
I understand how each of these methods work, but they all seem to have similar functions to one another, and I'm not sure as to what situation might call for what method.
See MDN:
The some() method executes the callbackFn function once for each element present in the array until it finds the one where callbackFn returns a truthy value (a value that becomes true when converted to a Boolean). If such an element is found, some() immediately returns true. Otherwise, some() returns false. callbackFn is invoked only for indexes of the array with assigned values. It is not invoked for indexes which have been deleted or which have never been assigned values.
You can see that here:
const arr = ['item 1', 'item 2', , 'item 3', , 'item 4', 'item 5'];
console.log(arr.some((item, index) => {
console.log(item, index);
return !item
}));
If I will explicitly replace the empty elements with undefined, then it will return true.
That's the difference between "never assigned a value" and "been assigned the undefined value".
The elements are actually empty and not undefined
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);
VM146:4 (7) ['item 1', 'item 2', empty, 'item 3', empty, 'item 4', 'item 5']
Thats the reason the some script behaves differently. This thread does a good job on explaining stuff
Check the array has empty element or not