JavaScript some() method

โœ๏ธ

JavaScript some method, how it works and why you need it

24 Nov, 2020 ยท 1 min read

Did you ever need to know if one of the elements in an array passed a test?

This is where the some() method comes in handy.

Let's keep using our product array, but let's add a discounted product.

We then want to test if some of our products are discounted.

Using the Javascript some() method

Let's start by creating an array of items.

const items = [
  { name: 'T-shirt plain', price: 9, discount: true },
  { name: 'T-shirt print', price: 20 },
  { name: 'Jeans', price: 30 },
  { name: 'Cap', price: 5 },
];

Now let's use the some() method to test if we have a discounted product in our array.

const discounted = items.some((item) => {
  return item.discount;
});

// Returns true

If we now remove the discount on our item, it will return false.

Another use case might be to check if all people are under a certain age.

const users = [
  { name: 'Bob', age: 60 },
  { name: 'Sarah', age: 20 },
  { name: 'Billy', age: 18 },
];

const ageRestriction = users.some((user) => {
  return user.age <= 18;
});

// Returns true

This returns true because billy is under the age of 18!

The syntax for some is as follows:

const new = original.some(function(value));

Inside our function, we can check on specific properties the value has.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next ๐Ÿ“–

JavaScript sending data between windows

9 Sep, 2022 ยท 4 min read

JavaScript sending data between windows

Using the native payment request JavaScript API

9 Aug, 2022 ยท 8 min read

Using the native payment request JavaScript API