Trying to understand this:
const _ = {};
_.map = function(list, callback){
var storage = [];
for(let i=0; i<list.length; i++){
storage.push(callback(list[i], i, list));
}
return storage;
}
_.map([1,2,3], function(val){return val+1;})
Why does the callback require 3 args, when we clearly need only one?
_.map = function(list, callback){
var storage = [];
for(let i=0; i<list.length; i++){
storage.push(callback(list[i])); //****** This works too!
}
return storage;
}
_.map([1,2,3], function(val){return val+1;})
Context: Doing a course on Frontend Masters, where they implemented it like the first version.
An Array#map method can have up to 3 parameters for its callback. mentioned here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
map((element) => { ... })
map((element, index) => { ... })
map((element, index, array) => { ... })
since you are not using the other two params index, array they would be undefined.
run the below code for both declarations to understand better.
_.map([1,2,3], function(val,index,arr){
console.log(val)
console.log(index)
console.log(arr)
})
It's because if you lookup at the current definition of the Array.prototype.map the callback function can receive up to three argument as you can see bellow.
map(function callbackFn(element) { ... })
map(function callbackFn(element, index) { ... })
map(function callbackFn(element, index, array){ ... })
map(function callbackFn(element, index, array) { ... }, thisArg)
Apart from the item at the given index on the array which the map function is call, you can receive the index and the array it self.
callbackFn
Function that is called for every element of arr. Each time callbackFn executes, the returned value is added to newArray.
The callbackFn function accepts the following arguments:
element
The current element being processed in the array.
index Optional
The index of the current element being processed in the array.
array Optional
The array map was called upon.
thisArg Optional
Value to use as this when executing callbackFn.