1

foo is equal to iCantThinkOfAName, but the iCantThinkOfAName has two parameters, and foo only one. I don’t understand how foo(2) returns num: 4.

function iCantThinkOfAName(num, obj) {
  // This array variable, along with the 2 parameters passed in, 
  // are 'captured' by the nested function 'doSomething'
  var array = [1, 2, 3];

  function doSomething(i) {
    num += i;
    array.push(num);
    console.log('num: ' + num);
    console.log('array: ' + array);
    console.log('obj.value: ' + obj.value);
  }
  return doSomething;
}
var referenceObject = {
  value: 10
};
var foo = iCantThinkOfAName(2, referenceObject); // closure #1
var bar = iCantThinkOfAName(6, referenceObject); // closure #2
foo(2);

/*
num: 4
array: 1,2,3,4
obj.value: 10
*/

4
  • what is num with foo(3)? 5 - what is num with bar(2) - 8 ... does that help? Commented Feb 17, 2017 at 3:58
  • by the way, foo(2) doesn't "return" anything Commented Feb 17, 2017 at 3:59
  • … and foo is not equal to iCantThinkOfAName. Commented Feb 17, 2017 at 4:00
  • 1
    Why don’t you understand it? It’s just how closures work. What did you expect instead? Commented Feb 17, 2017 at 4:01

1 Answer 1

3

foo is not equal to iCantThinkOfAName, it is equal to iCantThinkOfAName(2, referenceObject) which returns the inner function doSomething within a closure containing num (which is equal to the 2 you passed in), obj which is your referenceObject you passed in, and array = [1, 2, 3];.

When you call foo(2) you are directly calling that inner doSomething where i is your 2 you are passing in, which gets added to your num which was your original 2; thus, num within the closure, is now 4.

Sign up to request clarification or add additional context in comments.

1 Comment

This is actually a really clear and great explanation of what’s going on in the code and what each function does.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.