JS: Array.prototype.some

By Xah Lee. Date: . Last updated: .

Return true if the function f return true for at least one element.

This is done by evaluating f on each element in array in order. As soon as f(item) return true, exit the iteration and return true. Return false if none is true.

If myArray is empty, return false.

myArray must be a array object or array-like object. [see JS: Array-Like Object]

The function f is passed 3 args: • current_elementcurrent_indexmyArray.

If thisArg is given, it will be used as this value of f. If it is not given, undefined is used.

[see JS: “this” Binding]

// example of Array.prototype.some

const f = ((x) => (x === 3));

console.log(
    [1,2,3,4,5,6].some(f) === true
);
// true

Use “some” as Loop with Break

“some” is useful as a forEach with break.

[see JS: Array.prototype.forEach]

Here's example. Apply f to each element in order. Exit the loop when f returns true.

// using Array.prototype.some as loop with break

function f (x) {
    console.log ( x );
    return x === 3 ;
}

[1,2,3,4,5,6].some(f)

// prints

// 1
// 2
// 3

// as soon as f returns true, the iteration aborts

「some」 on Empty Array

some on empty array returns false.

// method “some” on empty array returns false
console.log(
    [].some(
        function (x) {return true;}
    )
);
// false

Array.prototype.every

[see JS: Array.prototype.every]

Reference

ECMAScript® 2016 Language Specification#sec-array.prototype.some

Array Topic

  1. JS: Array Basics
  2. JS: Understand JS Array
  3. JS: Create Array
  4. JS: Sparse Array
  5. JS: Array-Like Object
  6. JS: Array How-To

  1. JS: Array Object
  2. JS: Array.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth