Photo by Daniel Fazio on Unsplash
Usually, when we want to create loops, we'd prefer to use modern JS to do that with a nicer syntax than the old for's, however when some condition is matched, and we need to stop the loop in the middle we still dependent from the old for's loops, like in the example below:
const people = [
{name: 'Katie', gender: 'female'},
{name: 'Antony', gender: 'male'},
{name: 'Robin', gender: 'male'}
]
function isAllMales(people){
for(let x = 0; people[x]; x++) {
console.log(people[x].name)
if(people[x].gender === 'female') {
return false
}
}
return true
}
/* This function will return false and print:
Katie
*/
But there a better way to do that, isn't it? Some devs usually choose the filter or reduce method to do that; however, from a performance perspective, filter/reduce isn't the best approach once you need to run across the entire loop to discover something that sometimes is already available in the first iteration.
const people = [
{name: 'Katie', gender: 'female'},
{name: 'Antony', gender: 'male'},
{name: 'Robin', gender: 'male'}
]
const isAllMales = people {
const malePeople = people.filter(
(person) => {
console(person.name)
return person.gender === 'male'
}
)
return malePeople.length === people.length
}
/* This function will return false and print:
Katie
Antony
Robin
*/
So, to solve problems like this we can use Every or Some methods, Every is a way to iterate an array that will check if some condition happens in all the items when some item don't match with the condition the iteration will stop automatically.
const people = [
{name: 'Katie', gender: 'female'},
{name: 'Antony', gender: 'male'},
{name: 'Robin', gender: 'male'}
]
const isAllMales =
people => people.every(
(person) => {
console.log(person.name)
return person gender === 'male'
}
)
/* This function will print:
Katie
*/
You also can use the Some method to do this verification. It will stop the loop in case of no one of the items matches the condition.
const people = [{name: 'Katie', gender: 'female'}, {name: 'Antony', gender: 'male'}, {name: 'Robin', gender: 'male'}]
const isAllMales =
people => !people.some (
(person) => {
console.log(person.name)
return person gender === 'female'
}
)
/* This function will print:
Katie
*/
That's classy, isn't it? In our example, we need to output a console.log to illustrate how it works, but in real world this syntax could be even more cohesive:
const isAllMales =
people => people.every(
(person) => person gender === 'male'
)
// or
const isAllMales =
people => !people.some (
(person) => person gender === 'female'
)
If you want to know more about every and some take a look in MDN docs.
Thanks for reading this article! I also post some articles in my Medium account and Dev.to account, also I share some thoughts in my Twitter account.