7/27/18

The .every method i discovered today

Looking on react-redux example i found the following line:


  if (user && requiredFields.every(key => user.hasOwnProperty(key))) {
    console.log('no need to call "fetch"')
    return null
  }

Notice the usage of "every" statement.

Every

So, what is the advantage of "every"?
consider you have the following array:


const arr = [{name:'yoyo', active:true}, {name:'momo', active:true}, {name:'bobo', active:false}]

How can you quickly know if all users are active?
So, you can loop through the array with "forEach", like this

let everybodyIsActie = true;
arr.forEach(user => {
   if(!user.active) { // if even one is not active
     everybodyIsActie = false;
   }
})
if(everybodyIsActie) {
 console.log('everybody dance now!')
}

But, much more awesome is to use "every" statement:

if(arr.every(user => user.active)) {
 console.log('everybody dance now!')
}

No need to use any variables
Unlike "forEach" (which doesnt returns enything) "every" returns true if every array item fills the condition
See you in my next post!

No comments:

Post a Comment

Getting started with docker

It is very simple to get started usig docker. All you need to do-is download the docker desktop for your system Once you get docker syste...