Home > Mobile >  understanding the reason for different behavior in .every()and .some()
understanding the reason for different behavior in .every()and .some()

Time:05-27

I like using .every() and .some() in javascript and ran into a difference in their behavior and I didn't see an explanation as to why on MDN. According to MDN, if you run .every() on an empty array, the result is true because in mathematics all elements of the empty set will match a condition. But .some() will return false when run on an empty array.

const myArray = [];
const ev = myArray.every( elem => {
  elem === 'this is foobared';
});
const so = myArray.some( elem => {
  elem === 'this is foobared';
});

//  ev is true
//  so is false

I'm a bear of very little brain, but it seems like if every element of the empty set matches the condition, then some of the elements match the condition because if all all elements match, .some() will be true.

const myArray = [1, 2, 3, 4];
const ev = myArray.every( elem => {
  return elem < 10;
});
const so = myArray.some( elem => {
  return elem < 10;
});

// ev is true
// so is true

Is there any logic behind this?

Thanks for any explanation.

CodePudding user response:

The reason for this is that it allows the associative property of these operations to work properly.

This property requires the following equivalences:

array1.every(condition) && array2.every(condition) == array1.concat(array2).every(condition);

array1.some(condition) || array2.some(condition) == array1.concat(array2).some(condition);

Replace array2 with an empty array, and you'll see that defining [].every(condition) as true and [].some(condition) as false will ensure that the equivalences are achieved in the boundary cases.

This is similar to the way that true is the identity value for the && operator and false is the identity for the || operator.

CodePudding user response:

some(any) vs every(all): Basic Difference

Easily you can memorize every is [And &&] and
some is [Or ||]
let me show you some object array example.

Can read What is the difference between every() and some() methods

// Example
let users = [ {id:1, type: 'student'},  {id: 2, type: 'student'} ];
let isEveryStudent = users.every(user => user.type === 'student');
console.log('isEveryStudent', isEveryStudent);
// ```isEveryStudent``` is true because All users are student

users = [ {id:1, type: 'student'},  {id: 2, type: 'officer'} ];
isEveryStudent = users.every(user => user.type === 'student');
console.log('isEveryStudent', isEveryStudent);
// ```isEveryStudent``` is false because one of the user is officer

users = [ {id:1, type: 'student'},  {id: 2, type: 'officer'} ];
const isSomeOfficer = users.some(user => user.type === 'officer');
console.log('isSomeOfficer', isSomeOfficer);
// ```isSomeOfficer``` is true because one of the user is officer

  • Related