define array every method in javascript

What is Array Every Method in JavaScript?

The Array "every" method in JavaScript is used to check if all the elements of an array meet a certain condition or not. It returns a boolean value of either true or false based on the results of the condition.

Syntax:

array.every(callbackFunction(element[, index[, array]])[, thisArg])
  • array: The array on which the "every" method is called.
  • callbackFunction: The function to be executed for each element in the array. It takes three parameters: the element, its index, and the array itself.
  • thisArg: (optional) The value to be used as "this" when executing the callback function.

Example:

Let's say we have an array of numbers and we want to check if all the numbers are even or not using the "every" method.


let numbers = [2, 4, 6, 8];

let areAllEven = numbers.every(function(num) {
    return num % 2 === 0;
});

console.log(areAllEven); // Output: true

In the above example, we have declared an array of numbers and used the "every" method to check if all the numbers are even or not by using a callback function that checks if the remainder of each number when divided by 2 is 0 or not. Since all the numbers in the array are even, the "every" method returns "true".

Multiple Ways to Use:

There are several ways to use the "every" method in JavaScript, some of them are:

  • Using arrow function:

let numbers = [2, 4, 6, 8];

let areAllEven = numbers.every(num => num % 2 === 0);

console.log(areAllEven); // Output: true
  • Using "thisArg" parameter:

let obj = {
  factor: 2,
  isFactor: function(element) {
    return element % this.factor === 0;
  }
};

let numbers = [2, 4, 6, 8];

let areAllFactors = numbers.every(obj.isFactor, obj);

console.log(areAllFactors); // Output: true

In this example, we have defined an object "obj" with a "factor" property and a "isFactor" method that checks if an element is a factor of the "factor" property or not. We have then used the "every" method on the "numbers" array with the "isFactor" method as the callback function and passed the "obj" object as the "thisArg". This makes sure that the "this" keyword inside the "isFactor" method refers to the "obj" object and not the global object.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe