map is one of the most used, popular array methods in Javascript. It can also be referred as higher order function. Higher order function is a function which returns function or which accepts other functions as arguments.Let's understand about map function
many times you need to take an array and modify it according to your needs and you can easily achieve this with help of map method.
Syntax of map method
map method accepts a callback function which is executed on each of the element of the array. Callback function can also be written using arrow syntax
callback function accepts following arguments
element - It is the current element being processed in the iteration
Index - It is the index of current element being processed and it is optional
array - array on which the map method was called and it is optional
let's understand map method with an example
consider the above example where you have an array and you want to multiply all the elements of array by 2
Here map method accepts a callback function which is executed on each element of the array. Callback function takes el as argument, which is the current array element in the iteration and multiplies it by 2 and return a new array with all modified values. Thus map method return a new array to result variable with modified values.
If the array consists of multiple objects, then the callback function receives current object in each iteration
Thus array.map method is very useful when we want to modify array element according to needs and create a new array.
Comments
Post a Comment