Doubt with map()

function multiply(multi,…args){
return args.map((element)=>{
return multi*element;
});

};
// console.log(args)
var arr=multiply(3,1,2,3);
console.log(arr)

it is working fine and i am getting the desired output,but i don’t understand how map() creates a new array.
in line 3 when return will produce 3*1 =3 ,then again return will give 6 and finally 9 .so [3,6,9] will then be returned by 2nd line and stored in ‘arr’.
but meantime when then map() was running were was the output stored?

The map method returns a new array and so starts with a blank array. During each iteration of the arr in which it is called on, the function supplied is called on the iterated elements.

The args array is [1, 2, 3], so element (which represents each element of the args) starts as 1 and gets multiplied by 3, so 3 gets added to the new array, next element is 2 and gets multiplied by 3, so 6 gets added to the new array , and finally element is 3 and gets multiplied by 3, so 9 gets added to the new array. After the args array has been iterated over, the new array of [3, 6, 9] is returned.

1 Like

so the new blank array which map() creates is an temporary array whose address is only known by map() and is destroyed or deleted after map() completion.?

Without digging deep into the specs, I think It is not a temporary array. It is the final array which gets stored in memory whose reference gets assigned to arr in the line:

var arr = multiply(3, 1, 2, 3);
1 Like