Explain Closures!

Hey there, so I was working on the Arguments Optional challenge here. I solved the problem, but I don’t quite understand how the closures function works that I wrote. Here is the function that I made that I could use some advice on to understand what is going on. Specifically, I am confused about how the second number works when it is added on to the end of the function being called.

var args = Array.prototype.slice.call(arguments);
  var addNew = function(x) {
    return function(y) {
      if (!Number.isInteger(y)) {
        return undefined;
      }
      return x + y;
    };
  }; 
}
addTogether(2)(9);

Here it is:

function addTogether() {
var args = Array.prototype.slice.call(arguments);
  var addNew = function(x) {
    return function(y) {
      if (!Number.isInteger(y)) {
        return undefined;
      }
      return x + y;
    };
  }; 
}
addTogether(2)(9);

Sorry, I copied part of it out of a larger piece of code because it was only one piece that I had a question about. I’ll put the whole thing in.

function addTogether() {
  var args = Array.prototype.slice.call(arguments);

  var isNumb = function Numb(args) {
    for (i = 0; i < args.length; i ++) {
      if (!Number.isInteger(args[i])) {
        return undefined;
      }
    }
    return true;
  };    
  
  var addNew = function(x) {
    return function(y) {
      if (!Number.isInteger(y)) {
        return undefined;
      }
      return x + y;
    };
  }; 
  
  var addTwo = function(a,b) {
    return a + b;
  };
  
  if (!isNumb(args)) {
    return;
  } else if (args.length === 1) {
      return addNew(args[0]);
  } else if (args.length > 1) {      
      return addTwo(args[0], args[1]);
  }   
}

addTogether(2)(3);

HI.

If I’ve missed some subtle point about what you’re trying to achieve, I apologise, but…

function addTogether(a) {
return (function plus(b) {
return a + b
})
}

var result = addTogether(2)(7)
console.log(result)

will give you a function that employs a ‘closure’.

If you call it like this, it’s easier to see what’s going on

function addTogether(a) {
return (function plus(b) {
return a + b
})
}

var twoPlus = addTogether(2)

console.log(twoPlus)

var result = twoPlus(7)

console.log(result)

The function is returning a function. If you only give it one argument and assign the result to a variable, that variable will contain a function that you can then call. The top example just does both of these things at once.

This is called a closure because that first argument that you pass in gets “closed over” meaning that it’s available to the inner function when it eventually gets called.