Second arguments function

Tell us what’s happening:

I don’t understand what the return function(arg2) does exactly.
How does the function get that we are looking for the second argument? Is arg2 something in JS that it knows we are looking for the second argument or how does work?

Your code so far


function addTogether() {
var checker = function(num) {
  if (typeof num !== "number") {
    return undefined;
  } else return num;
};

if (arguments.length > 1) {
  var a = checker(arguments[0]);
  var b = checker(arguments[1]);
  if (a === undefined || b === undefined) {
    return undefined;
  } else {
    return a + b;
  }
} else {
  var c = arguments[0];
  if (checker(c)) {
    return function(arg2) {
      if (c === undefined || checker(arg2) === undefined) {
        return undefined;
      } else {
        return c + arg2;
      }
    };
  }
}
}
addTogether(2, 3)
addTogether("http://bit.ly/IqT6zt")
addTogether(5)(7);

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:

You know how you define a function with an argument passed into it:

function functionName(arg1) { ... }

Well that’s all that’s happening here except that instead of defining the function first and then returning it, it is combined into one step. Also, the function is not given an explicit name since we never call it directly.

As far as what it does, it’s a pretty simple if/else combo, returns undefined under certain circumstances and c + arg2 otherwise. The variable c is arguments[0] in the original function addTogether(). That’s part of the magic of JS, any variables that are in scope for this anonymous function can be accessed even after the original function has returned.

@bbsmooth thanks for the answer, I am not fully confident yet.

Am I getting it right that these cases are only used when the function is calles f(x)(y)?
And when we return the function(arg2) it’s called on (y), because (x) has already been used in the the main function?

Yes, if you only pass in one number arg to addTogether then it will return the anonymous function and you can then use that anonymous function to add another number to the original number passed into addTogether.

You could do this instead:

const anonFunc = addTogether(1);
anonFunc(2);

anonFunc holds the anonymous function that was returned by addTogether. In that function the variable c is set to 1 because that’s what we passed into addTogether. Since anonFunc is a function that takes one argument we can now call it and pass in that one argument (2 in this case) and it will return 3.

But we can clean those two lines up to just one:

addTogether(1)(2);

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