JavaScript Array#Every

Lemuel Uhuru
DevGenie
Published in
2 min readOct 12, 2018

Every once in a while you have to filter for the truth, thankfully and conveniently JavaScript offers us the every() method which does exactly that.

Method Definition:

It traverses an array instance, applying a callback function to each index with an assigned value, immediately returning false if a value does not pass the conditional within the callback and true if all elements within the traversed array pass.

Method Parameters:

The every() method accepts a required callback function as its first parameter and an optional ‘this’ value as its second.

The callback function accepts the current element, index, and array being traversed, as the first, second, and third parameters respectively.

For Example:

arrayInstance.every(callbackFunction, this) // every() method SignaturecallbackFunction(currentElement, index, array) {} //callback func signature

Example Data:

In our example we have a trivial social networking app and want to display a notification on a users profile when all of their friends are logged in. We’ll store our friends as objects within an array. Each friend will have the following properties:

  • Name -> String
  • Age -> String
  • Sex -> String
  • isLoggedIn -> Boolean
const friends = [{"name": "Kanye", "age": "19", "sex": "Male", "isLoggedIn": true},{"name": "Trump", "age": "30", "sex": "Male", "isLoggedIn": true},{"name": "George", "age": "14", "sex": "Male", "isLoggedIn": false},{"name": "Sarah", "age": "26", "sex": "Female", "isLoggedIn":false},{"name": "Hillary", "age": "28", "sex": "Female", "isLoggedIn": false},];

Challenge:

Create a function called isFullHouse, it should:

  1. accept an array of friends represented as objects
  2. return true if a friend is logged into their account, otherwise false.
// Callback function used to evaluate if a user is online
function isOnline(friend = {}) {
return friend.isLoggedIn === true;
}
// Function used to evaluate if all a users friends are online
function isFullHouse(friends) {
return friends.every(isOnline);
}
console.log(isFullHouse(friends));> false

Unfortunately, all of our friends are not logged in and as a result the every() method returns a boolean value of false.

Conclusion:

I hope you have gained a better understanding of how to use the every() method through a potential real world application. If you enjoyed this tutorial, please feel free to clap a few times and check out some of my other articles. Until next time, be well : ).

--

--