In this article, you will learn about the javascript Array built-in method Array.prototype.some()
. How does this method work in javascript?
This Array.prototype.some()
method is used to determine if any element of the array passes the test of the provided testing function. It returns true
if it finds an element for which the provided function returns true
; otherwise, it returns false
.
array.some(callback(element [, index [, array]]) [,thisParameter]);
This method takes 2 parameters as given below:
this
to be used while executing the callback function.The some()
does not change the original array. And it executes callback function once for each array element in order.
Some()
does not execute the callback function for array empty elements.
Here are some examples of Array.prototype.some()
method:
// function checking number is greater than 10
function isBiggerThan10(element, index, array) {
return element > 10;
}
console.log([2, 5, 8, 1, 4].some(isBiggerThan10));
// Output => false
console.log([12, 5, 8, 1, 4].some(isBiggerThan10));
// Output => true
//Checking whether a value exists in an array
const languages = ["JavaScript", "Python", "C++", "Java", "Go"];
function checkAvailability(arr, val) {
return arr.some((arrVal) => val === arrVal);
}
console.log(checkAvailability(languages, 'JQuery'));
// Output => false
console.log(checkAvailability(languages, 'Python'));
// Output => true
//Using some() on sparse arrays
console.log([1, , 3].some((x) => x === undefined));
// Output => false
console.log([1, , 1].some((x) => x !== 1));
// Output => false
console.log([1, undefined, 1].some((x) => x !== 1));
// Output => true
I hope this article will help you to understand the javascript Array built-in method Array.prototype.some().
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments