Arguments Optional : Can someone help me understand what is happeing here

Tell us what’s happening:
I couldn’t figure out how to pass tests 3 and 6 so used the solution to try to understand what’s happening.

I’m confused on what the function is actually doing on the last line. I tried to use debugger to watch what it was doing, I thought it might have been reducing the array to just the number but it didn’t look like that happened. Can anyone help explain what it is doing?

Also I tried to refactor in some other ways to make sure I understood how everything else was working together and found that trying to write the function func not as an arrow function(see example) broke it. Why would changing it from an arrow function to a longer version change how the function works? I tried reading up on arrow functions on MDN but couldn’t find anything. Thanks for any help.

Your code so far


function addTogether(p1, p2) {
if(typeof p1 !== "number") {
    return undefined;
};

//example
//let func = function(p2){example}

debugger;
let func = p2 =>
 typeof p2 === "number" ? p1 + p2 : undefined; console.log(func)
 return typeof p2 === "undefined" ? p2 => func(p2) : func(p2);

 


};
//addTogether(2);
addTogether(2)([3]);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36.

Challenge: Arguments Optional

Link to the challenge:

The code is a little hard to read because of the implicit returns and use of ternary.

Not sure if it helps but here it is re-written using normal functions, and if/else instead of ternary.

function addTogether(first, second) {
  if (typeof first !== 'number') {
    return undefined;
  }

  function sum(second) {
    if (typeof second === 'number') {
      return first + second;
    } else {
      return undefined;
    }
  }

  if (typeof second === 'undefined') {
    return function (second) {
      return sum(second);
    };
  } else {
    return sum(second);
  }
}

So in this part -

if (typeof second === ‘undefined’) {
return function (second) {
return sum(second);

It looks like it’s just running it back through the function that will return undefined.
I guess I just didn’t get how it strips the array to return the number

It is returning an anonymous function that accepts an argument. When called the anonymous function will run the sum function and pass it the argument. If the value provided to sum is a number it will run the if statement code block otherwise it will run the else block.

Not sure what you mean by this? It’s checking for typeof number, an array is not of type number so it returns undefined (for the test case addTogether(2)([3])).