paint-brush
Pocket Guide to Javascript Array Some Methodby@smpnjn
548 reads
548 reads

Pocket Guide to Javascript Array Some Method

by Johnny SimpsonJanuary 30th, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

The'some' method is useful for when checking if every element matches a certain criteria. It works like a loop - it loops over every element and checks if the callback function you gave returns true for any of them. For this function, `some` means anything more than 1 - so if even one element matches the criteria you define, the expression will return true.
featured image - Pocket Guide to Javascript Array Some Method
Johnny Simpson HackerNoon profile picture

I've already covered in another article the Javascript every method. It's useful for when checking if every element matches a certain criteria. The some method differs in that it checks if only 'some' elements pass a criteria. If some do, then the expression will return true overall. For this function, some means anything more than 1 - so if even one element matches the criteria you define, the expression will return true.


Let's look at an example:

let myArray = [ 5, 10, 15, 20, 25, 30 ]
let checkArray = myArray.some((x) => (x / 5) > 3)
// Returns true, since some elements, when divided by 5, return a number greater than 3
console.log(checkArray)


The some method takes one callback function, which can have 3 different arguments:

  • element - the element being iterated over. In the example above, I've named it x.
  • index - the index of array element we are iterating over currently.
  • array - the entire original array.


some works like a loop - it loops over every element and checks if the callback function you gave returns true for any of them. element and index let us check each element individually in our function, while array gives us easy access to the original array. Here is an example with all three:

let myArray = [ 5, 10, 15, 20, 25, 30 ]
let checkArray = myArray.some((el, index, array) => {
    if(el / 5 > 3 && index > 4 && array.length === 6) {
        return true
    }
})
// Returns true since all checks are true for "some" elements
console.log(checkArray)

If one element in some passes the test, then the function will stop - meaning it is quite an efficient way of testing if some array elements pass certain tests.

One Line statements with some

Earlier, you might have noticed we did this:

let myArray = [ 5, 10, 15, 20, 25, 30 ]
let checkArray = myArray.some((x) => (x / 5) > 3)
// Returns true, since some elements, when divided by 5, return a number greater than 3
console.log(checkArray)

... and even though we did not return true, the statement is still true. That is because one line functions when defined without curly brackets will return the result of a statement automatically. In this case, (x / 5) > 3 is returned by default, resulting in true.


Also published here.