The some() method of the Array class in JavaScript returns true if at least one element in the calling array satisfies the provided testing function.
There are 2 variations for the syntax of Array.some() method. They are:
some(callbackFn)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
callbackFn | required | A function to test each element in the array. It takes three arguments: element, index, and array. |
This method returns true if at least one element in the calling array satisfies the provided testing function.
Returns value of type Boolean
.
some(callbackFn, thisArg)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
callbackFn | required | A function to test each element in the array. It takes three arguments: element, index, and array. |
thisArg | optional | A value to use as this when executing callbackFn. |
This method returns true if at least one element in the calling array satisfies the provided testing function, using thisArg as the value of this inside callbackFn.
Returns value of type Boolean
.
In JavaScript, we can use the some() method to check if there are any even numbers in an array.
For example,
const arr = [1, 3, 7, 8, 10];
const isEven = element => element % 2 === 0;
const hasEvenNumber = arr.some(isEven);
console.log(hasEvenNumber);
true
We can use the some() method to check if there are any strings with a length greater than 3 in an array.
For example,
const strArr = ['a', 'bc', 'def', 'ghij'];
const isLengthGreaterThanThree = element => element.length > 3;
const hasLongString = strArr.some(isLengthGreaterThanThree);
console.log(hasLongString);
true
We can use the some() method with a thisArg to check if there are any elements in an array that satisfy a testing function using a specific context.
For example,
const arr = [5, 12, 8, 130, 44];
const context = { threshold: 100 };
function isGreaterThanThreshold(element) {
return element > this.threshold;
}
const hasElementGreaterThanThreshold = arr.some(isGreaterThanThreshold, context);
console.log(hasElementGreaterThanThreshold);
true
In this JavaScript tutorial, we learned about some() method of Array: the syntax and few working examples with output and detailed explanation for each example.