The some() method in JavaScript is used to test whether at least one element in the array passes the test implemented by the provided function. It returns true if any element passes the test; otherwise, it returns false.
Syntax
array.some(callback(element, index, array), thisArg);
Parameters
Parameters | Descriptions |
---|---|
callback() | A function to test each element of the array. It takes three arguments:
|
thisArg (Optional) | A value to use as this when executing the callback function. |
Return Value
Return Type | Description |
---|---|
Boolean | true if at least one element passes the test; false otherwise. |
Example 1: Testing for Even Numbers
This code demonstrates how to use the some() method to test if at least one element in the array is an even number.
let Arr = [1, 3, 5, 7, 8, 9]; let hasEvenNumber = Arr.some((num) => num % 2 === 0); console.log('Has Even Number:', hasEvenNumber);
Output:
Has Even Number: true
Example: Using thisArg
You can use the thisArg
parameter to set the context of the callback function.
let context = { threshold: 10 }; let Arr = [1, 3, 5, 7, 8, 9]; let hasNumAboveThreshold = Arr.some(function(num) { return num > this.threshold; }, context); console.log('Has Number Above Threshold:', hasNumAboveThreshold);
Output:
Has Number Above Threshold: false
Note:
The some() method stops iterating over the array if an element passes the test, and returns true. Otherwise, it continues until all elements have been tested or the callback returns true.
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
1 | 12 | 1.5 | 9.5 | 3 |