Array.prototype.map() & Array.prototype.forEach()

Array.prototype.map() & Array.prototype.forEach()

You must have used map() and forEach() for at least a 100 times but do you know the differences between these two higher order functions of JavaScript? Don't worry I got you covered.

First let's talk about higher order functions.

Don't go too deep into the concept, just simply remember that a higher order functions is a function that takes one or more functions as an argument or returning a function as a result. That's it!

Don't worry, we'll take a deep dive too.

Let's take a look at a higher order function

Let's first see how a simple function works:

function sum(a, b) {
  return a + b;
}

sum(4, 8); // returns 12

Above is a simple JavaScript function that takes two numbers as argument and returns their sum. It's probably the simplest JavaScript function.

Now we'll look at a higher order function that we'll create by ourselves

function ok(func) {
return func();
}

ok(function () { return 10 });    // Here we passed a function inside another function call.

The above function is a higher order function. It takes a function as an argument and also returns the same function. That's it! Does it look simple? Why? Because it is simple!!

Now coming to map() and forEach()

Array.prototype.map()

map() method creates a new array and the new array contains the results of calling the callback function on every element in the array.

Let's take a look at how this works in code

const numArr = [1,2,3,4,5];

const mapNumArr = numArr.map(num => num * num);

console.log(mapNumArr); // Output: [1, 4, 9, 16, 25]

What is happening here is that the map() function is creating a new array from the numArr array, populated with the results from the callback function.

Array.prototype.forEach()

forEach() function simply executes the callback function once for each element of the array.

const numArr = [1, 2, 3, 4, 5];

numArr.forEach(num => console.log(num)); 

// Output: 1
// Output: 2
// Output: 3
// Output: 4
// Output: 5

It simply executes the callback function for each element.

But there is a difference here, let's see

First is that the forEach() does not create a new array from the given array. But the map() function will create a new array from the given array.

Second is that the forEach() function does not expect a return but the map() function expects a return value.

Warning in the console

image.png

Have you ever seen this warning in the console? This is because we used a map() function here without a return statement. So map() function always expects a return statement. And if we don't give a return statement then it will show a warning in the console.

When to use which?

So map() function creates a new array. So you should not use it when you're not returning a value from the callback otherwise it will show a warning.