ExamplesReturn a new array with the square root of all element values: Show
const numbers = [4, 9, 16, 25]; Multiply all the values in an array with 10: const numbers = [65, 44, 12, 4]; function myFunction(num) { More examples below. Definition and Usage
Syntaxarray.map(function(currentValue, index, arr), thisValue) ParametersParameterDescriptionfunction()Required.A function to be run for each array element.currentValueRequired. The value of the current element.indexOptional. The index of the current element.arrOptional. The array of the current element.thisValueOptional. Default value undefined .A value passed to the function to be used as its this value.Return ValueTypeDescriptionAn arrayThe results of a function for each array element.More ExamplesGet the full name for each person: const persons = [ persons.map(getFullName); function getFullName(item) { Browser Support
ES5 (JavaScript 2009) fully supported in all browsers: ChromeEdgeFirefoxSafariOperaIEYesYesYesYesYes9-11map() is an array method that applies a function we provide to each element of an array and creates a new array with the results. Syk Houdeib, Front-end developer
In this “JavaScript iteration in the real world” series of articles, I want to share with you some of the most common JavaScript iteration methods using examples that resemble as closely as possible what their usage looks like in the real world. I will try to avoid `foo` and `bar` or overly complex examples. There won’t be a lot of mentions of your pets and friends either I’m afraid. Instead, we’ll take a deep look at how the method works, why we need it, and what it would look like in a typical modern front-end codebase. In the previous installment, we talked about the map()So let’s explore the So in the example above we have an array of products and we used `map()` to add an asterisk at the end of each name. Let’s take a closer look at it and see what this line really means.
In plain English, this line of code means: given an array called products, take each element in the array and add an asterisk to it. Then return a new array with all the transformed elements. When finished, store the new array in a variable called Of course, adding an asterisk to a name is a quick way to show how `map()` works, but doesn’t look realistic at all. So let’s bring “the real world” into our explanation. In the real worldLike in the previous article, we will continue with the realistic context on which to base our examples. We are working on the codebase of an online shop. The shop displays the products and their corresponding prices. A realistic thing we might need to do in an online shop is to apply a discount on our prices. Let’s say the holiday season has recently passed and to bump our sales we want to apply a 10% discount across the board on all of our products. That’s the kind of task where We will continue using the simple app I created especially to demonstrate this in action. You can check out the web app and see map in action, and you can see the code in its GitHub repo. But we will go through everything here first. Let’s start simple and then build up to what the final code will look like in our example with the 10% discount applied to all our prices. Let’s just think of the prices of our products on their own for a minute. Let’s invent an array of prices. Then say we simply want to knock off 1€ of each price.
This is However, in our shop, we won’t get an array that only has prices. We have an array of products, and each product is an object that has several properties. Price is one of those properties.
Now we are dealing with an object, and not a simple element in the original array. But fear not, `map()’ can handle this without breaking a sweat. We can map over products and apply a discount to our prices by accessing the price property on each product like this:
This will reach into the product object and pick out the price property to apply the discount on. But, there is a problem. This will return a new array which only contains the new prices, and we have lost all the other properties of the product object. We need all those properties to render our products correctly in the shop with their name and everything else. So we will need to copy all the properties of each product, modify only the price, then return the new product object. This way we will end up with an array of products identical to the original except for the modified price.
Now instead of returning a simple number on each iteration of the loop, we are returning an object. Let’s take a quick look at what is happening here, even if it is not directly related to how Now, this new product is added to our new array, and map picks up the next product from the original array and does the same to it too. And so on for each element in the array. Great, so far so good. We have our new product object with the new price. But we didn’t want to subtract 1€ randomly, we wanted to apply a 10% discount. So all we have to do now is get the formula that does this.
We don’t care much about how this formula works. The important bit is to see how map is creating a new array of products for us out of the old array and applying the discount formula to the price of each. If we apply this to our store, you will see how all the prices displayed change, but everything else remains the same. How does it workLike A higher-order function means it is a function that we can pass another function for it to do something with. The function we supply, referred to as a callback function, is passed as an argument. So it’s the first argument we pass within the round brackets of the method Once we pass our function to the map method, this provides us with three fixed arguments for our function. We will look only at the first for now.
The current element that map is working on is provided to us as the first argument. That’s the singular “product” or “price” we see in our examples above. It is a variable, and we can name it whatever we want. But it’s logical that for an array of products a single element of the array is one “product”, it’s a conventional way of naming the item out of an array of items. We can use this variable in the body of our callback function. That’s after the arrow of the arrow function here, where we can use this product variable (or price, or whatever else it is) to implement the function we want Remember that the original array stays intact and doesn’t get modified. We end up with two arrays, the original and the new one. This allows us to have access to both sets at the same time adding to the power of What’s moreWe have just seen how
The `element`, as we have seen, is the current element being processed. The index is the position of this currently selected element in the array, and the final argument is the original array itself we are iterating on. For example, this is what we will get if we log each product and its index on each iteration of filter()
Two things to keep in mind. If we are working only with a single argument the round brackets surrounding them are optional, so if you see `element` without the round brackets it’s the same thing, it just looks cleaner.
But we can only drop the round brackets if we are using only one argument. We need to keep them if we are using more than one. Secondly, we called the second argument “index” here, and the third argument “array”. But like “product” these are also variable names. You can name them what you want. You can call them “lito” and “hernando” and nothing would change. Remember it’s not the name that matters here, but the position of the argument. The first is always the element, the second is always the index, and the third is the array we started with. However, your obscure pop culture reference notwithstanding, we tend to name things in a way that makes it easier for readability. So the second argument is almost always called “index” or “i” by convention, and the third usually is “array” or “arr”. So far we have only seen map functions that are implicitly returning directly what comes after the arrow of the arrow function. But what happens if the function we want to supply is more complex and needs to be written on several lines? Then we have to add curly braces to enclose the code in the body of the function and explicitly specify what to return. Once we put curly braces after the arrow function it no longer implicitly returns anything, and that will produce an error. So we have to explicitly tell it what to return using the `return` keyword. What we return is what it will add to the new array.
The example above does exactly the same as our original which adds a 10% discount. But in this case, we decided to write it out on several lines for readability, saving the discounted price in a variable. And as you can see we added the curly braces, and the explicit `return`. Another way you will see `map()` being written is to write the function we are using separately (either storing it in a variable or with the `function` keyword) and then pass it as a callback function directly. This would look like this.
One last thing to remember, and that’s when not to use What it looked like prior to ES6With ES6 we have arrow functions and a lot of great stuff that make our code more readable. But it is important to know what things looked like before because you will come across this way of writing it in tons of older codebases that are still in use, and you will come across it in older examples on Stack Overflow and the like. This is how we wrote a map before ES6:
As you can see, before we got the arrow function we needed the `function` keyword, the arrow is gone and we need the curly braces and the `return` keyword. What it looks like in a for loopLet's pull away from the Wizard of Oz’s screen and look at what’s actually happening behind the scenes. Array methods are higher-order functions that simply have a loop at their heart doing all the actual work. We won’t need to write a for loop for something like this because that’s what `map()` is for. But it’s a good exercise to see what it looks like to understand what’s happening.
And if we go one step further and take a look at what
This is a simplified version of the implementation of map (based on an example I got from here) but serves to show you exactly what is happening when you call the map method, and when you pass the callback function, and what it returns at the end of the iteration. ConclusionArmed with a deeper understanding of what Why use map instead of array?Map is iterable
While an Array , as brought up in the question, is also iterable, a Map offers a better use-case for key-value mappings than an Object would. Being iterable has a number of benefits, just-in-time execution and guaranteed order being two examples.
Why should we use map in JavaScript?Map can be used when you want to perform an action on each element in a collection, and gather the results into a new array. In JavaScript, the "for loop" or "nesting" can complete the same task, but we can use map() to create more readable functions. Map can be created and initialized with the new Map() syntax.
When to use array vs map in JavaScript?In arrays and sets, the loop iterates over the values stored, and in maps, the loop iterates over each key-value pair. In sets and maps, the iteration happens in the insertion order. In arrays, iteration happens in the order of indices. You can also iterate over only keys or values of a map with a for…of loop.
What are the benefits of using the map () method?map() method allows you to iterate over an array and modify its elements using a callback function. The callback function will then be executed on each of the array's elements.
|