How to use Map | JavaScript

/ #JavaScript


JavaScript Map is a Higher-Order function and in this post I'll show you how to use it.

What is a Higher-Order function?

A higher order function is a function that operates on other functions. They can either take functions as arguments, or they can return them. In other words, either you pass inn a function or you get a function in return.

A quick example

First I will show you an example where you have an array of numbers. For each of the values, we want to add 1. This is how you would solve this without higher-order functions:

const arr1 = [1, 2, 3, 4, 5];
const arr2 = [];

for (let i = 0; i < arr1.length; i++) {
	arr2.push(arr1[i] + 2);
}

// Print the array

console.log(arr2);

// Will return
// [2, 3, 4, 5, 6]

This is how you solve it using a higher-order function (map):

const arr1 = [1, 2, 3, 4, 5];
const arr2 = arr1.map(function(item) {
	return item + 1;
});

// Print the array

console.log(arr2);

// Will return
// [2, 3, 4, 5, 6]

If you want to make it even shorter, you can use the arrow function syntax:

const arr1 = [1, 2, 3, 4, 5];
const arr2 = arr1.map(item => item + 2);

// Print the array

console.log(arr2);

// Will return
// [2, 3, 4, 5, 6]

Questions?

If any of this was unclear, feel free to leave me a reply below!

Comments

No comments yet...

Add comment

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.