avatarCoding In depth

Summary

The webpage provides an explanation of when to use various JavaScript array methods such as every(), some(), forEach(), and map(), illustrating their practical differences and use cases through examples.

Abstract

The JavaScript array standard library includes methods like every(), some(), forEach(), and map() that are essential for array manipulation. The article focuses on the practical implementation of these methods, highlighting the differences between some() and every() in checking array conditions, and between forEach() and map() in terms of return values and mutability. It clarifies that some() returns true as soon as a condition is met, while every() checks that all elements meet the condition and exits on the first falsy value. forEach() is used for iterating over elements without returning a new array, whereas map() is used when a new array with transformed elements is needed. The article also touches on performance, suggesting that map() can be faster than forEach() under certain conditions, but a plain loop is generally the fastest. The author recommends using forEach() for linear operations and map() when the returned array is utilized.

Opinions

  • The author emphasizes the practical application of array methods over theoretical explanations.
  • The preference of map() over forEach() is suggested when the returned array is necessary.
  • The article implies that understanding the iteration patterns of some() and every() is crucial for efficient code.
  • The author points out that map() is useful for chaining array methods, whereas forEach() does not support chaining.
  • It is mentioned that while map() does not mutate the original array, it can mutate the objects within the array if the callback function modifies them.
  • The author provides a cost-effective alternative to ChatGPT Plus (GPT-4), suggesting a service called ZAI.chat for similar performance at a lower price.
  • Performance comparisons are made, with the conclusion that plain loops are faster than array methods, but map() can outperform forEach() in certain scenarios.

When to use every(), some(), any(), forEach() and map() in JavaScript

JavaScript array standard library comes with a variety of methods. These methods help in finding output based on the input provided. There are plenty of articles but they are not focused on practical implementation.

Photo by Paweł Czerwiński on Unsplash

Check the attached stackblitz project.

some(any) vs every(all): Basic Difference

Is Array.any() exist in the JavaScript? The answer is no. However, Array.some() do the purpose of getting any elements. The method Some will return true when the first matching condition will be met. In the below code we have product array which consists of product name, subscription validity, and payment approval element.

let productArray =[
{productName:”Netflix”,isSubscriptionValid:true, isPaymentApproved:false},
{productName:”Amazon Video”,isSubscriptionValid:false, isPaymentApproved:false},
{productName:”Some Subscriber”,isSubscriptionValid:true, isPaymentApproved:false},
]

Find if at least one product has a valid subscription?

For this query, we want any, one element with a valid subscription. We can use some for this purpose.

let someresult = productArray.some(x=>{
console.log(`some ${x.isSubscriptionValid}. ${x.isPaymentApproved}`);
return x.isSubscriptionValid==true
});
//Result
true

Find if all product has a valid subscription?

For this purpose, we can use Array.every. The method every() iterate each element and exits when it finds falsy value.

let everyresult = productArray.every(x=>{
console.log(`every ${x.isSubscriptionValid}. ${x.isPaymentApproved}`);
return x.isSubscriptionValid==true});
//Result
false

some(any) vs every(all): Iteration Pattern

The method some() always check the single condition that returns a truthy value. Hence some() always return when the first condition returns true. every() method is just inverse of some. every() method keeps iterating till the last element if it finds all returning value true. However every returns of first false. In the below example since the first product payment is approved, hence some() iterate only once and exit in first return.

let productArray =[
{productName:"Netflix",isSubscriptionValid:false, isPaymentApproved:true},
{productName:"Amazon Video",isSubscriptionValid:false, isPaymentApproved:false},
{productName:"Some Subscriber",isSubscriptionValid:true, isPaymentApproved:true},
]
//Exit in first iteration and return true
let someresult = productArray.some(x=>{
console.log(`some ${x.isSubscriptionValid}. ${x.isPaymentApproved}`);
return x.isSubscriptionValid==true
|| x.isPaymentApproved==true
});

In the below example some() will iterate two times and exit when both condition return falsy value.

let productArray =[
{productName:”Netflix”,isSubscriptionValid:false, isPaymentApproved:true},
{productName:”Amazon Video”,isSubscriptionValid:false, isPaymentApproved:false},
{productName:”Some Subscriber”,isSubscriptionValid:true, isPaymentApproved:true},
]
//Exit in second iteration and return false
let everyresult = productArray.every(x=>{
console.log(`every ${x.isSubscriptionValid}. ${x.isPaymentApproved}`);
return x.isSubscriptionValid==true || x.isPaymentApproved==true});

forEach vs map: Return value

forEach and map both iterate elements. The choice of choosing one over another depends on the situation. The basic difference is map always returns a new array with the same size and forEach does not return any value. Returned array in .map() is always the same size as the original list and always return only the transformed or changed object. .map() does not return all elements in the array.

In the below example the product name will be printed and the result on the left side is undefined.

let forEachresult = productArray.forEach(x=>
console.log(x.productName));

However, if we are using .map() method then it always returns a new array. The original copy of the array remains the same. The return result will be a new transformed array. Now here .map() returned a list with the same size of original element but with product name.

let mapresult = productArray.map(x=> x.productName);
console.log(productArray);
console.log(mapresult);
//result
//["Netflix", "Amazon Video", "Some Subscriber"]

forEach vs map: Function chaining and immutability

map can be easily chained with other arrays methods some(), every(), filter() etc. However, you can not chain forEach() with any other array method.

let mapresult = productArray.map(x=> x.productName).some(y=>y.productName=='Netflix');

The method map does not mutate the original array and return the new object. However, if callback is used inside the array it can mutate the original object and will return a new array with only mutated elements.

In the below example the productArray will not get mutated and mapresult array will be of product name starting with hello.

let mapresult = productArray.map(x=> ‘Hello ‘+ x.productName);

Similarly, forEach also does not mutate the original object however if callback is used it can transform the original object.

forEach vs map: When to use?

Thumb rule is if you are not using a returned array, do not use .map() method. forEach() method can be used if performing linear operation.

forEach vs map: Speed!!!

So if we are comparing speed plain loop is always faster than any array method. In certain conditions .map() runs faster than .forEach() method.

Check the test performed in the link.

Summary

We have seen a practical difference between every() and some(). We have also seen the difference between forEach and map in terms of return value, the mutability of the array, chaining of array, and when to use.

JavaScript
Arrays
Array Methods
Array Functions
Programming
Recommended from ReadMedium