Open In App

How to use every() or some() methods in JavaScript ?

In JavaScript, the every() and some() methods are array methods used to check the elements of an array based on a given condition.

Table of Content



every() Method

The every() method tests whether all elements in the array passed the condition given to the callback function. It returns a boolean value indicating whether all elements satisfy the condition.

Syntax:

array.every(callback(element[, index[, array]])[, thisArg])

Parameters:

Return Value:

It returns true, if all elements of array passed the given condition. Otherwise, it will return false.



Example: The below example implements the every() method with an array in javaScript.




const arr1 = [1, 2, 3, 4, 5];
const arr2 = [3, 5, 8, 9, 11];
const res1 =
    arr1.every(num => num < 10);
const res2 =
    arr2.every(num => num < 10);
console.log(res1, res2);

Output
true false

some() Method

The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a boolean value indicating whether at least one element satisfies the condition.

Syntax:

array.some(callback(element[, index[, array]])[, thisArg])

Parameters:

Return Value:

It returns true, if any one element of the array passed the given condition. Otherwise, it will return false.

Example: The below code implements the some() method to check elements of an array for a passed condition.




const numbers = [1, 2, 3, 5, 7, 9];
const odd = [1, 3, 5, 7, 9];
 
const res1 =
    numbers.some(num => num % 2 === 0);
const res2 =
    odd.some(num => num % 2 === 0);
console.log(res1, res2);

Output
true false

Article Tags :