JavaScript Glossary - Lesson #2

JavaScript Array .every() Method

The every method checks that each element in an array passes a set test. This method will return true if all the elements pass the set. Once an element that fails the test is found, the method returns false.

let result = [10, 5, 20, 100].every(function(number){
    return number < 150

console.log(result) // true
// Create new array
const array = [20, 21, 23, 15, 2];

// Create condition
const isLessThan100 = (number) => number < 100;

// Apply function
let result = array.every(isLessThan100);

// output: true

The every method:

  • Takes a callback function that implements a test
  • Checks if all the elements pass the test
  • Returns true if every element passes the test.
  • Returns false an element fails test
const isCorrect = array.every(callback[,thisArg])

callbackFunction(function) The function that tests each of the elements of the array. The callback function is required and can take three parameters:

  • element: This is the element currently being executed - required.
  • index: The index of the current item - optional.
  • array: The array that is currently being processed - optional.

thisArg (this) (optional) An argument passed to be used as the this value in the callback - optional

This method will return true of every element in the array passes the test and if the array is empty. It returns false if an element within the array fails the test.

When expecting a boolean return value after testing all the elements within an array.

// Age of users
const ages = [17, 18, 22, 25];

// Age threshold to drive
const drivingAge = 16;

// Test users for who can drive
let canDrive = ages.every(function(age){return age >= drivingAge;});

// output: true

.every() method can be used to test all items in an array of objects using either the object keys.

// Array of students
const students = [
  { name: 'John', score: 50 }, 
  { name: 'Peter', score: 60 }, 
  { name: 'James', score: 55 }

// Threshold Score
const passScore = 50;

// Test students
const studentsPassed = students.every(student => student.score >= passScore);

// output: true

Want to improve your coding and design skills?

I'm continually researching the best practices and tools for coding.
Join 50,000+ developers looking to make cool stuff.

We value your privacy. 1-click unsubscribe.

Chris Sev

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created which was acquired.


What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)