DEV Community

Discussion on: Mastering Hard Parts of JavaScript: Callbacks I

Collapse
 
flippsn profile image
Flippsn • Edited

Hi Ryan! I'm pretty new on my learning journey for JavaScript and would have a question regarding exercise 5.

I generally do get the structure of callbacks, but there is one thing I simply cannot wrap my head around:
Why does the anonymous function within the forEach function require the "item" parameter (see below on line 3).

function mapWith(array, callback) {
const newArr = [];
forEach(array, (item) => {
newArr.push(callback(item));
});
return newArr;
}

Since forEach(array, callback) does execute "callback(array[i])" I simply cannot wrap my head around why this solution would not work:

function mapWith(array, callback) {
let arrNew = [];
forEach(array, () => {
arrNew.push(callback());
});
return arrNew;
}

Maybe you could provide some additional insights? Thank you!

Collapse
 
mehran1801 profile image
Mehran Khan • Edited

Q: " Since forEach(array, callback) does execute "callback(array[i])" I simply cannot wrap my head around why this solution would not work: "

Answer:
The reason it would not work is because callback(array[i]) will not push the resulting element to the output array, as a result you will get 'undefined' because it hasn't pushed the results into the resulting array. It would simply apply the callback on each item/element. so what we need to do is define another callback method in forEach function.

for(let i=0; i<array.length; i++){
output.push(callback(array[i]))

Basically we want to wrap up this entire functionality into callback of forEach function.

Q: " Why does the anonymous function within the forEach function require the "item" parameter"

forEach(array, (item) => {
newArr.push(callback(item));
});

So for every item that we pass in we want it to push the result of calling the callback with that item into the resulting array. so let's say we have array [1,2,3] the item parameter would call 1 first and apply the callback and push to the resulting array and so on...

There are multiple arguments being passed into multiple parameters and it is kind of confusing but if you step through it line by line using console log statements, it will eventually make sense.
Happy Coding!