Some() method in Javascript explained with examples

In this article some method is explained with examples. It is a useful method with various use cases we could us it for.

Some method definition

According to MDN the some() method tests whether at least one element in the array passes the test implemented by the provided function.

Note: some() does not execute the function for array elements without values and some() does not change the original array. Look at this simple example:

function isBiggerThan10(element, index, array) {
  return element > 10;
[2, 5, 8, 1, 4].some(x => x > 10);  // false
[12, 5, 8, 1, 4].some(x => x > 10); // true

Additionally we have used arrow functions to make it neater and more readable. Some will apply the function once for each element present in the array until it finds one where callback returns a truthy value. Immediately it returns true then.

Moreover we can shorten the whole code to one function as some accept the function as its array argument:

[2, 5, 8, 1, 4].some((element, index, array)=> element > 10); // false
[12, 5, 8, 1, 4].some((element, index, array)=> element > 10);// true

Really sweet and clean. Huh! Lets have a look at another examples.

Some method to check availability inside array

OF course there are other use cases for some. We might need to check if a user has admin privileges.

const userPrivileges = ['user', 'user', 'user', 'admin'];<br/>userPrivileges.some( element => element === 'admin');
// will be equal to true

There is also another example of checking if something exists inside array:

const fruits = ['apple', 'banana', 'mango', 'guava'];

function checkAvailability(arr, val) {
  return arr.some(arrVal => val === arrVal);

checkAvailability(fruits, 'kela');   // false

In addition we have a similar example with numbers :

const arr = [2, 5, 8, 1, 4]
function checkAvailability(arr, val) 
  return arr.some(
             return val === arrVal;
           } );

checkAvailability(arr, 2);
checkAvailability(arr, 87);

some and includes methods difference

Similarly includes checks if an array contains a certain value. It’s similar to .some(),but instead of looking for a condition to pass, it looks if the array contains a specific value:

const names = ['sophie', 'george', 'waldo', 'stephen', 'henry'];<br/>names.includes('waldo');
// will be equal to true

In this short post I explained some method which has its own use cases. We also saw its difference with includes method. Respectively we will explore all array methods in the future articles like we did before. Thanks fo reading.

© 2019
Azadeh Faramarzi

This site is created and maintined by Azadeh Faramarzi , A passionate developer, sport and code lover who loves to share and write when she has some time.