Open In App

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

Last Updated : 22 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

  • every(): Checks if all elements in an array satisfy a condition.
  • some(): Checks if at least one element in an array satisfies a 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:

  • callback: Function to test for each element.
  • element: The current element being processed in the array.
  • index (Optional): The index of the current element being processed in the array.
  • array (Optional): The array some() was called upon.
  • thisArg (Optional): Object to use as this when executing the callback.

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.

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:

  • callback: Function to test for each element.
  • element: The current element being processed in the array.
  • index (Optional): The index of the current element being processed in the array.
  • array (Optional): The array some() was called upon.
  • thisArg (Optional): Object to use as this when executing the callback.

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.

Javascript




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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads