DEV Community

Cover image for map: a JavaScript Iterator
Michellebuchiokonicha
Michellebuchiokonicha

Posted on • Updated on

map: a JavaScript Iterator

Last time, we started a series on Javascript Iterators. We will now continue with the next iterator, the map. If you missed the first topic in this series, here is a link to read through https://dev.to/michellebuchiokonicha/javascript-higher-order-function-3jeh

A map creates a new array from the existing array. This is unlike the forEach iterator returns undefined. When mapping an element, you do not need to push elements into a new array as a map creates a new array automatically after calling the function. Similar to the forEach, the first parameter to a map iterator is a callback function and the callback function can have a maximum is three parameters. The value of the array currently being called, the index of the array currently being called, and the array itself currently being called.

Let us use the same example we used in the forEach series and solve it using the map iterator.

Write a function that returns a new array with all its values increased by ten.

Function increasedByTen(ten) { ten.map(function(val){ return val + 10 }); } If the value of ten = [2,4,6,8,10] increasedArray = [12,14,16,18,20].

You can also create a new map object using the new Map() method. Here is an example:

var twenty = new Map([ ["twentyone", 21], ["twentyTwo", 22], ["twentyFour", 24] ]); You can use the get() method to get the value for the key in the map created.

Another map method is the set() method which sets the value for the key in the new Map

var twenty = new Map(); twenty.set("twentyone", 21); twenty.set("twentyTwo", 22); twenty.set("twentyFour", 24);

other map methods like the delete(), has() and more can also be used.

When mapping as an arrow function, it looks like this: map((element) => { /* … */ })

When mapping as a callback function, it looks like this: map(callbackFn)

When mapping as an inline callback function, it looks like this: map(function (element) { /* … */ })

They all get the same results the difference is the syntax you choose which does not change anything.

Next, we will talk about the filter iterator.

My Twitter Handle: https://twitter.com/mchelleOkonicha

My LinkedIn Handle: https://www.linkedin.com/in/buchi-michelle-okonicha-0a3b2b194/

Top comments (0)