The some()
method in javascript is used to check if at least one element in the array satisfies the condition specified in its callback function. This method returns false
if none of the elements satisfies the condition.
let numbers = [2, 4, 6, 8, 100];
let check = numbers.some(function (num) {
return num === 100;
});
console.log(check); // true
If there are no elements that meet the condition then it returns false
.
let numbers = [2, 4, 6, 8, 100];
let check = numbers.some(function (num) {
return num === 200;
});
console.log(check); // false
In the above example, the array numbers
does not contain 200
, hence, it returns false
.
The callback function exits immediately when the condition is met and it does not loop through the remaining elements. To check this we will make use of the index
parameter.
let numbers = [2, 4, 6, 8, 100];
let check = numbers.some(function (num, i) {
console.log(i);
return num == 4;
});
console.log(check);
/*
OUTPUT:
0
1
true
*/
As you can see from the output, the function exits as soon as the condition is met in the second iteration.
The callback function of the some()
also takes a third argument which is the array itself.
let numbers = [2, 4, 6, 8, 10];
let check = numbers.some(function (num, i, arr) {
console.log(i);
console.log(arr);
return num == 200;
});
console.log(check);
/*
OUTPUT:
0
[2, 4, 6, 8, 10]
1
[2, 4, 6, 8, 10]
2
[2, 4, 6, 8, 10]
3
[2, 4, 6, 8, 10]
4
[2, 4, 6, 8, 10]
false
*/