Skip to content

Commit

Permalink
docs(blog): update some post (#6453)
Browse files Browse the repository at this point in the history
  • Loading branch information
necatiozmen authored Nov 5, 2024
1 parent 216f01b commit fa27de9
Showing 1 changed file with 110 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ image: https://refine.ams3.cdn.digitaloceanspaces.com/blog/2022-10-25-js-some/so
hide_table_of_contents: false
---

**_This article was last updated on February 2, 2024 to organize content for better understanding of Javascript some method._**
**_This article was last updated on November 4, 2024 to include performance considerations and comparisons with other iteration methods for a better understanding of the JavaScript `some` method._**

## Introduction

Expand All @@ -28,12 +28,20 @@ Steps we'll cover:
- [JavaScript `Array.prototype.some`: Details of the Callback Function](#javascript-arrayprototypesome-details-of-the-callback-function)
- [How `Array.prototype.some()` Works?](#how-arrayprototypesome-works)
- [How to Use JavaScript Array `some` Method?](#how-to-use-javascript-array-some-method)
- [When to Use JavaScript `some()`](#when-to-use-javascript-some)
- [`some()` with Large Arrays - Tips for Efficiency](#some-with-large-arrays---tips-for-efficiency)
- [**Early Stop Saves Time**](#early-stop-saves-time)
- [**Keeping the Callback Simple**](#keeping-the-callback-simple)
- [**When You Need to Check Every Item**](#when-you-need-to-check-every-item)
- [When to Use JavaScript `some()`?](#when-to-use-javascript-some)
- [Using JavaScript `Array.prototype.some` to Test Arrays of Nested Objects](#using-javascript-arrayprototypesome-to-test-arrays-of-nested-objects)
- [JavaScript `some()` With `thisArg` Argument](#javascript-some-with-thisarg-argument)
- [JavaScript `some(callback, thisArg)` Doesn't Work With Arrow Functions](#javascript-somecallback-thisarg-doesnt-work-with-arrow-functions)
- [JS `some(callback, thisArg)` Works With Non-Arrow Functions](#js-somecallback-thisarg-works-with-non-arrow-functions)
- [Modifying the Caller Array](#modifying-the-caller-array)
- [Comparing `some()` with `find()` and `every()`](#comparing-some-with-find-and-every)
- [**`some()`** – Checks if Any Item Matches](#some--checks-if-any-item-matches)
- [**`find()`** – Finds First Matching Item](#find--finds-first-matching-item)
- [**`every()`** – Checks if All Items Match](#every--checks-if-all-items-match)

## What is JavaScript some method?

Expand Down Expand Up @@ -88,6 +96,57 @@ console.log(isThereEvenNumber); // true

In the above chunk of code, `even` is our callback function where we apply the logic for testing if the item is an even number. We then pass `even` to `some()` which is invoked on `numbers` array. Apparently, we have at least one even number in `numbers` so `even` returns `true`. As a result, `some()` also returns `true`.

## `some()` with Large Arrays - Tips for Efficiency

I’ve put together a few tips and examples for using JavaScript’s some() method in a way that’s efficient with large arrays.

### **Early Stop Saves Time**

The real value of `some()` is that it can short-circuit at the first match and thereby save a lot of processing time with large arrays.

```javascript
const largeArray = Array.from({ length: 100000 }, (_, i) => i); // large array of 100,000 items

const hasNumberGreaterThan50000 = largeArray.some((num) => num > 50000);

console.log(hasNumberGreaterThan50000); // true, stopped at 50,001 and saved time
```

Here, `some()` short-circuits and bails early since it finds a match – it's considerably faster.

### **Keeping the Callback Simple**

Since `some()` calls the callback for each item until it finds a match, a simple callback keeps things efficient.

```javascript
const users = Array.from({ length: 100000 }, (_, i) => ({
id: i,
active: i === 99999,
}));

// Find the first active user
const hasActiveUser = users.some((user) => user.active);

console.log(hasActiveUser); // true, stops as soon as it finds the active user
```

Above, `some()` will stop on the active user when found using just a simple callback for performance.

### **When You Need to Check Every Item**

If you have to go through every item in an array for things like checking complex conditions across all items, sometimes `filter` or `reduce` works better.

```javascript
// Use `filter` when you need to check all items
const complexCondition = users.filter(
(user) => user.id % 2 === 0 && user.id > 5000,
);

console.log(complexCondition.length); // Outputs all users who match the condition
```

For cases where you want every match, `filter` makes more sense than `some()`, as it’s designed to "collect" all items meeting a condition.

## When to Use JavaScript `some()`?

`Array.prototype.some` is used in situations that involves fairly complex tests to be performed on an item, such as the division operation in the `even` function above.
Expand Down Expand Up @@ -350,6 +409,55 @@ As we can see, `numbers` is being mutated twice in the first call to `divisible(

This shows that the callback function processes the value of an item as it finds it at traversal and disregards the changes made to it when and after it is at that index.

## Comparing `some()` with `find()` and `every()`

I wanted to show a quick comparison of `some()`, `find()`, and `every()`, since each one is particularly strong for different scenarios with arrays.

### **`some()`** – Checks if Any Item Matches

The `some()` function tests whether _any_ item in the array fulfills a condition. It will short-circuit, that is, stop, the very first moment it finds a match as it makes its way through an array. This is a tremendous method whenever you want a fast check of something because all it needs to return is a "yes" or "no" answer.

```javascript
const numbers = [1, 2, 3, 4, 5];
const hasEven = numbers.some((num) => num % 2 === 0);

console.log(hasEven); // true, stops at the first even number
```

When you need to check if some item is satisfying the condition, then you should use `some()`.

### **`find()`** – Finds First Matching Item

`find()` goes one step further and actually _returns_ the first item that matches the condition. It's helpful when you would rather have the specific value, not just a boolean.

```javascript
const people = [{ name: "Alice" }, { name: "Bob" }, { name: "Charlie" }];
const foundPerson = people.find((person) => person.name.startsWith("B"));

console.log(foundPerson); // { name: 'Bob' }, stops after first match
```

Use `find()` when you want to retrieve the matching item itself, not simply know if one exists.

### **`every()`** – Checks if All Items Match

On the other hand, `every()` checks whether _each_ of the items in an array passes a test. This method tests all items and returns `true` if all items pass the test; otherwise, it stops on the first mismatch.

```javascript
const ages = [18, 22, 30];
const allAdults = ages.every((age) => age >= 18);

console.log(allAdults); // true, all ages are 18 or over
```

Use `every()` when you want to confirm every single item in the array passes a certain test.

In a nutshell:

- **`some()`** to check if at least one item matches.
- **`find()`** to return the first match.
- **`every()`** to confirm all items in the list match.

## Summary

In this post, we played around with the **JavaScript some** method which helps us test whether an array has at least one item that passes the test implemented using a callback function. We saw that the callback function could take only three arguments. Additional arguments can be bound to its execution context by setting its `this` value with a `thisArg` passed to `some()`.
Expand Down

0 comments on commit fa27de9

Please sign in to comment.