.map method in JavaScript

Let’s start with .map inBuilt function.
The
map()method is used to iterate through the array and complete the function by creating a new array, without changing the given parameter Array***//SYNTAX
arr. map(callback(currentValue), thisArg)***
Let’s see an example of Why MAP is used:
// Add 2 to each array element
let array = [1,2,3,4]
let result = []
for(let i = 0;i<array.length ; i++){
result.push(array[i]+2)
}
console.log(result) // output = [ 3, 4, 5, 6 ]
Explanation of code
Let’s take the
array with 4 Elements//Here is an Array let array = [1,2,3,5]Then Again
FOR Loop, which iterates through the array and takes eacharray[i]value and push it into a new variable array by adding it to the result.let result = [] for(let i = 0;i<array.length ; i++){ result.push(array[i]+2) }Above Example, Here for adding the 2 to each element of the array. We used for loop to iterate in each and take an extra variable called result to give output.
But the coder becomes efficient when he solves the problem in a shorter and smart way
so, just can't we do it better? YES OR NO!!!!!
💡 YES!!!!! For better use and efficient work, MAP was made as an inbuilt function. So, let’s see What it is!!!!
let array = [1,2,3,4]
const addElementWith2 = (array) =>array.map(num => num + 2)
console.log(addElementWith2(array)) // output = [ 3, 4, 5, 6 ]
Explanation of code
Let’s take the
array with 4 Elements//Here is an Array let array = [1,2,3,5]When we use the Map function,
We take a new variable function with
Constthen we pass the argument asArray.Then
.maptakes the action ofForloop and takesArray[i] as an argument with name numAnd then
call back of functioncontinues and gives theresult
const addElementWith2 = (array) =>array.map(num => num + 2)
console.log(addElementWith2(array))

💡 YES!!!!! Just in one line, we have finished the array problem. By using Map Function
Key Points of the MAP method
.map inBuilt Function accepts only function.
Either write the function at the same pace or just create a function and call back it from .map
This method accepts two parameters
function(currentValue, index, arr)
currentValue*: It is a required parameter and it holds the value of the current element.*
index*: It is an optional parameter and it holds the index of the current element.*
arr*: It is an optional parameter and it holds the array.*
Gives a new array as output with the filtered condition
we can use objects inside the list and destruct while writing the function
💡 Can we use the objects????
Yes!!! we can but objects should be encoated within the List




