Why JavaScript Arrays are More Powerful Than You Think

If you are a JavaScript programmer, chances are you have used Arrays. Chances are you have used them a lot. Arrays are one of the most important and useful tools in JavaScript, but chances are you are not using them to their full capacity.

Take a look at the following code snippet:

var arr = [1,2,3,4,5];
var aboveThree = false;
for(var i = 0; i < arr.length; i++){
if(arr[i] > 3){
aboveThree = true;
}
}
console.log(aboveThree); //True

What does this code do? It will print out true if at least one of the elements in the array is greater than three. Although this is a fairly simple program it may be hard to understand what it does at first glance. It would become even harder to read with more complex code within the for loop. Is there a better way to do this? Let’s try it.

var arr = [1,2,3,4,5];
var aboveThree = false;
arr.forEach(function(element){
if(element > 3){
aboveThree = true;
}
});
console.log(aboveThree); //True

This code does the exact same thing, but in a slightly more readable way. The function forEach calls the callback function for each element of the array in order to check to see if any of the elements are above the number three. Using forEach instead of a standard for loop makes it easier to understand, especially if you have lots of complex calculations inside the loop. Now take a look at the following:

var arr = [1,2,3,4,5];
var aboveThree = arr.some(function(element) {
return element > 3;
});
console.log(aboveThree); //True

We just took advantage of the Array.prototype.some() function. Using this function we not only did we make the code shorter, it is now even easier to read!

There are many functions just like Array.prototype.some() that can be used to truly harness the true power of JavaScript arrays. In my experience, many JavaScript programmers are not aware of these powerful functions and end up reinventing them time and time again. Below are just a few more examples.

Array.prototype.forEach

The forEach method, as discussed earlier, calls a function for each item in the array. The parameters of the function passed into forEach are:

  1. element — The current element being processed in the array.
  2. index—The index of the current element being processed.
  3. array—The array that forEach() was called upon.

Array.prototype.some()

Array.prototype.some() returns true if at least one of the elements in an array passes the test implemented by the function parameter. The parameters for the function passed to Array.prototype.some() are the same as forEach().

Array.prototype.every()

This function is similar to Array.prototype.some() except that it will return true only if every element of the array passes the given test. The parameters are the same as some() or forEach(). An example of every() is shown below:

var array = [1,2,3,4,5];
var allAboveThree = array.every(function(element){
return element > 3;
});
var allBelowSix = array.every(function(element){
return element < 6;
});
console.log(allAboveThree); //False
console.log(allBelowSix); //True

Array.prototype.join()

Have you ever seen someone do something like this?

var array = ["Hello","World","Goodbye","World"];
var arrayString = "";
for(var i = 0; i < array.length; i++){
arrayString += array[i];
}
console.log(arrayString); // Hello World Goodbye World

Can we make this a little better?

var array = ["Hello","World","Goodbye","World"];
var arrayString = array.join();
console.log(arrayString); // Hello World Goodbye World

Much better.

Array.prototype.map()

Array.prototype.map() is a convenient way to map each value in an array to a new item in another array. One example is shown below:

var person1 = {name:'Zack',favoriteFood:'pizza};
var person2 = {name:'Steve',favoriteFood:'hamburger'};
var person3 = {name:'Jane',favoriteFood:'cheesecake'};
var people = [person1,person2,person3];
var foods = people.map(function(element){
return element.favoriteFood;
});
console.log(foods); //[ 'pizza', 'hamburger', 'cheesecake' ]

The map() method creates a new array with the results of calling a provided function on every element in this array. In the example above the new array contains the value returned by the function parameter, or in other words, each persons favorite food. The parameters of the map() callback is the same as the forEach() callback.

Array.prototype.filter()

Take a look at the following example code:

var array = [1,2,3,4,5];
var aboveThree = [];
array.forEach(function(element){
if(element > 3)
aboveThree.push(element);
});
console.log(aboveThree); //[4,5]

JavaScript arrays have a method for this called filter:

var array = [1,2,3,4,5];
var aboveThree = array.filter(function(element){
return element > 3;
});
console.log(aboveThree); //[4,5]

The filter() method creates a new array with all elements that pass the test implemented by the provided function. This is very useful when you want to find or remove only certain elements of an array. The callback method for filter() is the same as forEach() or map().

Array.prototype.reduce()

Array.prototype.reduce() is a little trickier to understand but can be really helpful. The reduce() method applies a function against an accumulator and each value of the array has to reduce it to a single value. This example should help the understanding a little:

var array = [1,2,3,4,5];
var sum = array.reduce(function(prevValue,element){
return prevValue + element;
});
console.log(sum); //15

The reduce() callback uses a prevValue (an initial value can be passed as the second parameter to reduce, it is defaulted to 0) to accumulate to some total. The callback can also have index and array passed in as parameters.

These are some of the most useful functions for arrays. You can learn more about them here at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array. So now you can finally use arrays like a pro.

Show your support

Clapping shows how much you appreciated Zack Porter’s story.