Confusion areound returning function in case of one argument

function addTogether() {
let args = Array.from(arguments)
return args.some(n => typeof n !== "number") 
? undefined
: args.length > 1
? args.reduce((acc, n) => (acc += n), 0)
: n => (typeof n === "number" ? n + args[0] : undefined);
}

addTogether(2);

Would someone please help me understand how the above solution works to return a function if one argument is passed to addTogether function. thanks

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:85.0) Gecko/20100101 Firefox/85.0.

Challenge: Arguments Optional

Link to the challenge:

This is definitely not the easiest code to read. The function is being returned here:

: n => (typeof n === "number" ? n + args[0] : undefined)

This is an anonymous arrow function that takes one argument (n).

The easiest way to read the return statement is to think of it as a bunch of if/else statements:

if (args.some(n => typeof n !== "number") === true) {
 return undefined;
}
else if (args.length > 1) {
  return args.reduce((acc, n) => (acc += n), 0);
}
else {
  return n => (typeof n === "number" ? n + args[0] : undefined);
}
1 Like

Very well explained and I recalled the anonymous function now :slight_smile: thanks a lot