JavaScript Array some() Tutorial

In this section we will learn what the Array some() method is and how to use it in JavaScript.

JavaScript Arrays some() Method: (JavaScript check if in Array)

When we want to look for an element that has a specific criterion in an array and we only looking for one match, the `some()` method is the method to be used for.

The `some()` method is used to run a test on every element in an array. Basically, when we want to exam the elements in an array, we can use this method.

With this method, if only ONE element in the target array passed the test (we define this test in some() method), the final result of this method will be true. Otherwise, if none of the elements passed the test, then the final result becomes false as well.

Note: the first element in an array that matches the criteria set in the some() method will cause the method to stop checking other elements in the array and it will return the value “true” as the final result.

Array some() Syntax:

array.some(function(currentValue, index, arr), thisValue)

Array some() Method Parameters:

The `some()` method takes two arguments.

The first argument is a reference to a function. For each element in the target array, the `some()` method will call the reference function.

The arguments that will be passed to this function are:

  • The first argument is the element of the array that the function is called for.
  • The second argument is the index number of this element.
  • The third argument is a reference to the target array.

Inside this function, we define a set of instructions that, at the end, should return either the value `true` or `false`.

Other than the function, the `some()` method takes a second argument as well. This second argument, which is optional, is a reference to an object that will bind to the `this` keyword in the target function that we passed as the first argument.

Array some() Method Return Value:

The final result of the `some()` method is a Boolean value.

If the result of ANY element in the function was `true` the final result of the `some()` method becomes also `true`.

Otherwise, if the result of calling the function for ALL elements returned `false` the final result for the `some()` method becomes `false` as well.

Example: using Array some() method in JavaScript

const arr = [1,2,3,4,5,"Twitter"];
function eve(value, index, arr){
  return typeof value =="string"?true: false; 
}

const final = arr.some(eve);
console.log(final);

Output:

true

Example: JavaScript check if it’s in array via some() method

const arr = [1,2,3,4,5];
function eve(value, index, arr){
  return typeof value =="string"?true: false; 
}

const final = arr.some(eve);
console.log(final);

Output:

false

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies