JavaScript map()
Let's learn what the map() is. And do some coding practice.
Let's get started!
What is the map()?
The simplest and easiest answer is :
- map() is a higher-order function.
- Iterate over an array and call a specific function on every element of the array.
- map() doesn't change the original array
- But, It creates a new array that contains the results from the iteration over the elements of the array
map() Parameters :
- function()
- current Element
- Index (Optional)
Where can we use a map().?
Let's assume, we have an array of numbers and we need to transform the array by multiplying each element by itself.
Like this: [1,2,3,4] => [1,4,9,16]
Get Soha - JavaScript Developer’s stories in your inbox
Join Medium for free to get updates from this writer.
So, instead of using a loop, You can achieve it using a map().
arr1 = [1, 3, 4, 6, 7, 8, 9, 10, 45, 78, 90, 123, 124];
let newarr = arr1.map((ele) => ele * ele);
console.log(newarr)To begin with, write the array name then the dot operator, and then the map.
Like this: arr1.map()
Then, you can create a separate function and pass it inside the map as an argument or you can create a function directly inside the map, either way, both syntaxes are valid.
You can also write a function inside the map with a function keyword then function name and all that.
I personally prefer arrow functions, so I created an anonymous arrow function that takes a parameter ele . The main point is, the parameter ele takes an element from the array and multiplies it with itself, the same process repeating for each and every element of the array. And lastly, it will return the new array after the transformation is complete.
Now, let's take another example. What if I want to transform the numbers of an array into binary or octal?
First, write the logic. I’m using a javascript built-in method toString() to do it.
The
toString()returns a number as a string. You can specify aradixfor converting numeric values into strings, which is optional. Basically, the base to use.It can be 2 for binary, 8 for octal, and 16 for hexadecimal.
Now let's write the function for it using the map().
let arr = [1, 4, 6, 89, 09, 45, 21, 122, 678, 900];
let binaryArray = arr.map((i) => i.toString(2));
console.log(binaryArray);That's it. I hope you understand the concept of the map() function.
Follow for more.







