A Deep Dive Into the JavaScript Some() Method

Written by iggy | Published 2023/07/05
Tech Story Tags: web-development | javascript | blogging-fellowship | programming | array-methods | arrow-functions | authorization | hackernoon-top-story

TLDRThe some() method determines if at least one array member satisfies the test defined by the given function. It returns true if it finds an element in the array for which the specified function returns true; otherwise, it returns false. Because this is a method, it accepts arguments, giving you greater flexibility over what you can do with an array.via the TL;DR App

Today, let's take a look at another JavaScript array method, which is the some() method. We will be learning how to determine if an item exists in an array using the some() method.

As always, the code examples in this article are written in the JavaScript language. Therefore, knowledge of the language is required for proper understanding. Without further ado, let's dive in.


What is the JavaScript some() method?

The Javascript some() method determines if at least one array member satisfies the test defined by the given function. It returns true if it finds an element in the array for which the specified function returns true; otherwise, it returns false. It makes no changes to the array.

Let's review this code snippet for a better understanding of this method:

const basket = ["oranges", "apples", "pineapple", "yam"]

basket.some(bas => bas.length === 3)

// true

basket.some(bas => bas.length <= 1)

// false

We simply try to test if one of the fruits’ lengths in the basket array is exactly equal to 3. At least in the array, a member complies with this test; it’s “yam” in this case. Our expected result would be true. The second condition checks if there’s any fruit length less than or equal to 1. This would result in a false because we obviously don’t have any length less than or equal to 1.


How do I use the JavaScript some() method?

The javascript some() method is easy to use; let me show you how.

Let’s start off by understanding how the syntax is written.

The syntax is written by simply surrounding the word 'some' with a parenthesis '()' as follows:

some()

Because this is a method, it accepts arguments, which gives you greater flexibility over what you can do with an array using the some() method.

They are as follows:

  1. Element
  2. Index
  3. Array

Element

The element parameter indicates the current element that is being processed in the array.

Index

The index is just the index of the current element that’s been processed in the array.

Array

This is the array in which we call the some() method.

Now that we understand the syntax, let’s see what the complete method looks like.

some((element, index, array) => { /*... */ })

As you can see, we have the three parameters included in the code snippet above, which provides a clear example of how to build this method.

Depending on your needs, you can choose to skip certain characteristics. Similar to the index, you may offer it as one of the options if you want extra details about the array. All the criteria do not always have to be included.


Three ways of writing the JavaScript some() method

The three common ways of writing Javascript are as follows:

  1. Arrow function
  2. Inline callback function
  3. Callback function

Arrow function

The arrow function was introduced in ES6, which attempts to solve some problems faced by the traditional function. This function can also be used with the some() methods:

some((element, index, array) => { /*... */ })

Inline callback function

We have the ability to write the callback function in the some() method without storing it in a variable.

const basket = ["oranges","apples","pineapple","yam"]

 const result = basket.some(function (element, index, array)) {

 return element.length >= 7

})

console.log(result)

Callback function

This style can be written by first declaring the function and storing it in a variable, then passing it as a callback to the some() method, like so:

const basket = ["oranges","apples","pineapple","yam"]

function callBack(bas){
   return bas.length === 7
} 

const result = basket.some(callBack)

console.log(result)


Use cases

  1. Validating form inputs
  2. confirming an item's existence
  3. Authorization and access control

making form inputs valid

When processing form submissions, thesome() function can be used to determine which input fields satisfy specific requirements. For example, you could verify that any inputs contain valid email addresses or that at least one required field is filled out.

I will give you an example of how this might look.

const formInputs = document.querySelectorAll('input'); 

const isAnyInputEmpty = Array.from(formInputs).some(input => input.value === ''); 

if (isAnyInputEmpty) { 
   console.log('Please fill in all required fields.'); 
}
else { 
  console.log('Form submitted successfully.');
}

In the code sample, we ensure the user does not submit an empty field; we want to notify them if they leave it blank immediately. And if they meet the requirements by submitting at least the relevant data, we want to handle the submission.

Confirming an item’s existence

If we have a cart of products or a data structure in our web application, we can use some() to determine if a specific product exists. This is particularly helpful when we want to perform certain actions based on whether an item is present or not. Let’s have a look at this code sample that explains it better.

const shoppingCart = ['shoes', 'T-shirt', 'trouser'];

const itemPresent = shoppingCart.some(item => item === 'trouser');

if (itemPresent){ 
  console.log('Product exists in the cart.')
} else { 
console.log('Product does not exist in the cart.')
}

We check to see if we have a ‘trouser’ in the shopping cart. We log into the console when we confirm it’s in the cart.

Authorization and access control

When implementing user authentication and authorization systems, we can make use of some() to check if a user has at least one required permission or belongs to any of the specified roles. This allows us to control access to certain functionalities or resources.

const userRoles = ['admin', 'editor']; 

const permissions = ['admin', 'moderator']; 

const hasRequiredRole = permissions.some(role => userRoles.includes(role)); 

if (hasRequiredRole){ 
console.log('Access granted.')
} else { console.log('Access denied.'); }

In the code sample, we made use of the combination of includes() and some() methods to grant permissions based on the user’s roles. If a user’s role aligns with the required permission, we grant them access; otherwise, we deny them access.


Takeaways

On a final note, the javascript some() method is used for testing conditions. It does not change the original array. They accept three parameters: element, Index, and array', where the element parameter indicates the current element that is being processed in the array and the index parameter is the “index” of the current element that has been processed in the array.

Thanks for reading my review of JavaScript's array method, specifically the some() method. What did you think of the explanation? Will you be giving it a try?

Let me know your thoughts in the comments below, and please follow me on HackerNoonfor future articles.


Written by iggy | Software Engineer.
Published by HackerNoon on 2023/07/05