Undefined variables in arrow functions

I’m having difficulty understanding the arrow function part of the code from the lesson…
args.reduce((a, b) => a + b, 0);

I found this link below which is helpful but it doesn’t explain how the arrow function itself seems to magically figure out what a and b are the first time the code runs. I understand how the reduce method works itself just not how args become a and b inside the anonymous arrow function given that it is a separate function (callback). It would be helpful to see the actual definition of the reduce method but I haven’t found it by googling.

It would really be nice for learning sake to be able to see javascript compiler going line by line with explanation of each action it takes. That way it would be obvious at what point and how args become a variable in the reduce callback.

  **Your code so far**

const sum = (x, y, z) => {
const args = [x, y, z];
return args.reduce((a, b) => a + b, 0);
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36

Challenge: Use the Rest Parameter with Function Parameters

Link to the challenge:

With regards to this, have you tried looking it up on MDN?

It’s definitely not magic. All array methods pass arguments to the callback. In simple terms, the method loops the array, calls the callback, and passes the arguments. The only real difference is the number of arguments passed to the callback and their values.

reduce(function(previousValue, currentValue, currentIndex, array) { /* ... */ }, initialValue)
map(function(element, index, array) { /* ... */ }, thisArg)


1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.