Let's Connect
aura menu

Array helper methods – alternative for “for loop” ?

Divami

TreeImage
TreeImage

Arrays are the most used data structures. There are different ways to loop over arrays in javascript, starting from the traditional for loop to the array helper methods. 

The conventional way to perform operations on arrays is – ‘for loop’. But hey! Did you know that there is a much more effective and easier way to do the same? Has this set you thinking? Well, a not-so-recent but rarely used are – “The array helpers”. So, what is so special about them?

Array helpers can be used to:

  • loop through an array of elements (which can be done using traditional for loop),
  • perform functions over each element,
  • Search for an element in an array,
  • filter elements,
  • reduce elements into a single value and many more…

Array helper methods:

forEach() :-

This array helper method accepts function (which performs operations on the array elements) as an argument that will be called for each element of an array.

Syntax:  arr.forEach((currentElement, index, arr) => {});

When compared to other methods like map and filter (which will be discussed later in this blog), forEach method cannot be used for chaining because it always returns undefined. 

Even if you explicitly try to return anything, the result will be undefined. The below example explains this scenario:

Screenshot_1.png

Hence, forEach() can be used when the requirement is to perform operations on each and every element of an array without expecting a return value.

Example: 

var arr = [1, 2, 3]; arr.forEach((element, i, arr) => { console.log(element + arr[i]); }); Output: 2 4 6

map() :-

This array helper method accepts a function that iterates through all the elements of an array but the difference here, when compared to forEach(), is, this function always returns a new array with the results returned from the provided callback function.

map() does not mutate the actual array but returns a new array. Using map() when you are not using the returned value is an anti-pattern. Prefer using forEach() in such cases.

Syntax:  arr.map((currentElement, index, arr) => {});

Example:

var arr = [1, 2, 3]; var result = arr.map((element, i, arr) => {    return element * arr[i];  });  console.log(result);    Output:  (3)[1, 4, 9]

filter() :-

This array helper method filters an array of elements based on a condition. filter() method returns a new array of elements that satisfies the provided condition.

filter() method executes the callback function on every element and constructs a new array with the elements for which the condition returns true.

Syntax:  arr.filter((currentElement, index, arr) => {});

Example:

var arr = [10, 20, 3, 40, 5]; var result = arr.filter(element => element % 2 == 0); console.log(result); Output: (3)[10, 20, 40]

Here, in the below example, the filter() is not used correctly.

Example:

var arr = [1, 2, 3]; var result = arr.filter(element => {   return element * 10; }); console.log(result); Output: (3)[1, 2, 3]

Hence, the filter() method returns the elements of the array instead of adding 10 to each element. 

find() :-

This array helper method is used to find an element from the array of elements. find() method returns the first element that satisfies the provided condition.

The key difference here, when compared to filter() is, filter() returns all the elements that satisfies the condition whereas find() returns the first element.

Syntax:  arr.find((currentElement, index, arr) => {});

If we consider the same example which we used for filter, here the output is 10.

Example:

var arr = [10, 20, 3, 40, 5]; var result = arr.find(element => element % 2 == 0); console.log(result); Output: 10

some() :-

This array helper method checks if at least one of the elements satisfies the provided condition. some() method returns a boolean value. 

some() method executes the callback function on each and every element until it finds one element for which the callback returns true.

This method returns true if one element from the array of elements satisfies the condition. Otherwise it returns false.

The difference between find() and some() is, find() returns value whereas some() returns true or false.

Syntax:  arr.some((currentElement, index, arr) => {});

Example:

every() :-

This method checks if each and every element of the array satisfies the condition and returns true only if all the elements of an array satisfies the condition.

every() method executes a callback function on each and every element of the array until it finds an element for which the callback returns false. If such an element is found, it returns false. Otherwise it returns true.

In short, some() returns true if at least one element matches the criteria whereas every() returns true only if all the elements match the criteria.

Syntax:  arr.every((currentElement, index, arr) => {});

For the example used in some() method, every() returns false.

Example:

var arr = [10, 20, 3, 40, 5]; var result = arr.every(element => element % 2 == 0);  console.log(result);    Output:  false

For an empty array, every() method returns true considering that all the elements of an empty array will always satisfy the provided condition.

Example:

var arr = []; var result = arr.every(element => element % 2 == 0);  console.log(result);    Output:  true

reduce() :-

This method executes a callback function that reduces an array into a single element. The callback function to reducer() takes 4 arguments:

  • Accumulator: If the initial value is provided in the callback, the accumulator value is set to the initial value. Otherwise,
  • accumulator value will be set to array’s first element’s value. This will hold the result of reduce function.
  • CurrentElement: It is the current element of the array.
  • Index: Current index of array.
  • Array: Source array.

Syntax:  arr.reduce((currentElement, index, arr) => {}, initialValue);

Example:

var arr = [1, 2, 4, 6, 8]; var result = arr.reduce((total, element) => total + element);  console.log(result);

Output: 

21

Example: (with initial value)

var arr = [1, 2, 4, 6, 8];

var result = arr.reduce((total, element) => total + element, 100);

console.log(result);
Output: 

121

If the array is empty and no initial value is set, TypeError will be thrown. Because as said, accumulator takes initial value if set or takes the first element of an array as its value.

Example:

var arr = []; var result = arr.reduce(element => element + 1);  console.log(result);    Output:  error: Uncaught TypeError: Reduce of empty array with no initial value

All these methods do not mutate the array on which these methods are called. They make things easier by reducing the amount of code that you have to write to perform any operation.

We hope this blog would have piqued your interest in knowing more about these methods. Go ahead, use them in your code and watch the magic unleash. Time to bid “for loop” goodbye? Well, it’s anybody’s guess!!

butterfly
Let'sTalk
butterfly
Thanks for the submission.