;

Javascript Array - some() Method


Tutorialsrack 29/10/2022 Jquery Javascript

In this article, you will learn about the javascript Array built-in method Array.prototype.some(). How does this method work in javascript? 

Array.prototype.some()

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

Syntax
array.some(callback(element [, index [, array]]) [,thisParameter]);

This method takes 2 parameters as given below:

  • callback: This parameter holds the function to be called for each element of the array. This function takes the mentioned parameters below:
    • element: This parameter holds the current element of the array.
    • Index(Optional): This parameter holds the index of the current element within the array.
    • array(Optional): This parameter holds the reference to the original array.
  • thisParameter(Optional): This parameter holds the context to be passed as 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:

Examples
// 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!


Related Posts



Comments

Recent Posts
Tags