The some() method tests whether any of the array elements pass the given test function.
Example
some() Syntax
The syntax of the some() method is:
arr.some(callback(currentValue), thisArg)
Here, arr is an array.
some() Parameters
The some() method can take two parameters:
- callback - The function to test for each array element. It takes in:
- currentValue - The current element being passed from the array.
- thisArg (optional) - Value to use as
thiswhen executing callback. By default, it isundefined.
some() Return Value
- Returns
trueif an array element passes the given test function (callbackreturns a truthy value). - Otherwise, it returns
false.
Notes: The some() method does not:
- change the original array.
- execute
callbackfor array elements without values.
Example 1: Using some() Method
Output
true
In the above example, we have used the some() method to find out whether any element of the ageArray array contains a value less than 18.
At first, we created the callback function checkMinor() that returns age less than 18.
We have then passed callback to the some() method as ageArray.some(checkMinor) that checks for elements less than 18 and returns true.
Example 2: some() Method to Check Result of Students
Output
At least one of the students failed.
In the above example, we have used the some() method to find out if any of the students have scored marks less than 40.
We have passed callback in the method as scoreObtained.some(studentIsPassed) which returns
truebecause scoreObtained contains at least one element i.e. 20 which is less than 40.
Since the test expression in the if statement is true, the program prints- At least one of the students failed.
Recommended Readings: JavaScript Array every()