DEV Community

Cover image for JavaScript Array Methods, Under the Hood, Part 2/2
Ethan Groene
Ethan Groene

Posted on • Originally published at javascript.plainenglish.io

JavaScript Array Methods, Under the Hood, Part 2/2

Thanks for coming to part two of this series on JS array methods. If this article is your first encounter with the series, and you want to read the first part first, check it out here. As the title of this article suggests, I’ll be giving you an alternative way to look at a few additional common JS array methods, & that is by using for loops to accomplish the same tasks. I’ll be covering the Math.max(), Math.min(), .reverse(), .filter() , & .reduce() methods. Hopefully, the examples I present here will bring you some clarity, in case you find some of these methods hard to understand. Let’s get started.


Math.min() , Math.max()

The purpose of these methods is to return the lowest or the highest number in a series of numbers. You can either enter the numbers as parameters or call this method on an array by passing in the array with the rest operator. Let’s look at some examples, shall we?

// RETURN THE SMALLEST VALUE IN AN ARRAY:
// Using a 'for' loop:
function findMinValueInArray(array) {
  let min = array[0];
  for (let i = 0; i < array.length; i++) {
    let currentNum = array[i];
    if (currentNum < min) {
      min = currentNum;
    }
  }
  return min;
}
findMinValueInArray([33, -5544, 55, 66]); // returns: -5544

// Using Math.min():
function findMinValueInArray(array) {
  return Math.min(...array);
}
findMinValueInArray([33, -5544, 55, 66]); // returns: -5544
Enter fullscreen mode Exit fullscreen mode

As you can see, using Math.min() requires much fewer steps, reducing your chances of making a mistake along the way. Math.max() functions in the exact same way, but the ‘for’ loop we could use in its place looks slightly different than that of Math.min(). Let’s take a look at that:

// RETURN THE LARGEST VALUE IN AN ARRAY:
// Using a 'for' loop:
function findMaxValueInArray(array) {
  let max = array[0];
  for (let i = 0; i < array.length; i++) {
    let currentNum = array[i];
    if (currentNum > max) {
      max = currentNum;
    }
  }
  return max;
}
findMaxValueInArray([33, -5544, 66, 55]); // returns: 66

// Using Math.max():
function findMaxValueInArray(array) {
  return Math.max(...array);
}
findMaxValueInArray([33, -5544, 66, 55]); // returns: 66
Enter fullscreen mode Exit fullscreen mode

.reverse()

This method can be called on an array in order to reverse the order in which its elements appear. Once done, it overwrites the order of the original array. Let’s see first how we could do this with a for loop, then by using the method itself:

// REVERSE ORDER OF ARRAY'S ELEMENTS
// Using a 'for' loop:
function reverseArray(array) {
  let reversedArray = [];
  for (let i = array.length - 1; i >= 0; i--) {
    reversedArray.push(array[i]);
  }
  return reversedArray;
}
reverseArray([1, 2, 3, 4, 5]); // returns: [5, 4, 3, 2, 1]

// Using .reverse():
function reverseArray(array) {
  return array.reverse();
}
reverseArray([1, 2, 3, 4, 5]); // returns: [5, 4, 3, 2, 1]
Enter fullscreen mode Exit fullscreen mode

Again, using the array method is much more efficient. When using a for loop, we’d have to declare an empty array, reversedArray at the beginning of the function, then loop through the given array in reverse, pushing each element to reversedArray, then return this array once the loop stops running. Even for a relatively simple example like this, the array method makes it much less likely that we’ll mess something up.

.filter()

The purpose of this method is to return an array of elements in a given array that satisfy a condition.

Let’s pretend we have an array of bank accounts, each of which has a balance property, & let’s return an array of accounts that have no money in them.

// Using a 'for' loop:
function getClientWithNoMoney(array) {
  let acctsWithZeroBalance = [];
  for (let account of array) {
    if (account.balance === 0) {
      acctsWithZeroBalance.push(account);
    }
  }
  return acctsWithZeroBalance;
}

// Using .filter():
function getClientWithNoMoney(array) {
  return array.filter((account) => account.balance === 0);
}
Enter fullscreen mode Exit fullscreen mode

As you can see, if we use a ‘for’ loop, we’d have to complete several more steps than if we simply use the .filter() method, in that we’d need to initialize an empty array to which we push accounts that meet a condition specified in the loop we use to iterate through the array of accounts. Finally, we’d need to return the array containing the appropriate accounts. Again, you can see that we have many more opportunities (maybe that’s not the best word ;) ) of making a mistake if we use a ‘for’ loop instead of the method.

.reduce()

The final method I’ll cover, .reduce(), executes a callback function, as defined by you (or whoever is writing the code), on each element of an array. As it iterates through the array, it passes in the return value from the calculation on the preceding element & finally returns a single value.

The most simple illustration of .reduce() can be seen by using it to add up all the values of an array, but let’s take it one step further & use it to calculate the average of an array of numbers:

// With 'for' loop:
function getAverage(array) {
  let sum = 0;
  for (let i = 0; i < array.length; i++) {
    sum += array[i];
  }
  return sum / array.length;
}
getAverage([10, 20, 30, 40]); // returns: 25

// With .reduce():
function getAverage(array) {
  return (
    array.reduce((cv, acc) => {
      return cv + acc;
    }) / array.length;
  );
}
getAverage([10, 20, 30, 40]); // returns: 25
Enter fullscreen mode Exit fullscreen mode

While using a for loop, we need to initialize a variable that represents the sum of all numbers in the array, which will be incremented by the current value in each iteration. Then, this sum will be divided by the length of the array to get the average. In this example, using .reduce() doesn’t save all that much code, but it still reduces (pun intended) the likelihood we’ll make a silly mistake while defining a variable or setting up the loop.


So there were a few more examples of how some common JS array methods would work if we use 'for' loops instead. The list of JS array methods is pretty extensive, & I think I would be boring you if I wrote about all of them, as I think writing about super techy things like this would stretch the bounds of my creative-writing skills. Either way, I don't have the time do so at the moment, as my goal with this two-part series was to unpack how some of the more-common methods work, & to give you an appreciation for the fact they exist.

If you would like me to explain how some array methods work, & I haven’t written about them here, let me know in a comment here. Additionally, if you have any praise or criticism, I’d be happy to hear that too. If you think others would find this useful, please share it with them.

Again, if you’d like to read part one, where I demonstrate how some other array methods would work with loops, go here.

Thanks for reading!

Originally published to Medium for JavaScript in Plain English on February 13, 2023

Top comments (0)