2

I'm a beginner and I'm taking an interactive online class. Closures were the topic of discussion today. The following question was asked, "How many closures are created in the following code?".

function addUp (c, d) {
  return c + d;
}

function doubleDown (c) {
  return addUp(c, c);
}

I said two and my answer was based on this. I was told the answer is one closure is created. The reason given was convoluted and obviously didn't make sense to me. I've read over this, this, and this where the following statement is made: enter image description here

So my question is where am I going wrong with my interpretation of closures? Any additional resources I can be pointed to will be appreciated.

Community
  • 1
  • 1
  • The question should probably be "How many functions are *used as* closures in the following code?" As in: which of these two functions make use of capabilities that only closures have – stholzm Mar 13 '17 at 19:53
  • I would also say 2 based on the "all functions in ecmascript are closures" statement. – John Boker Mar 13 '17 at 19:59
  • 1
    Nothing is wrong with your interpretation. If you can explain your choice (and also why 0 might be another suitable answer that's not wrong), that's probably worth much more than saying what they wanted to hear. It's a good question in an oral exam, it's a horrible question in a multiple choice test. – Bergi Mar 13 '17 at 22:10
  • @Bergi i guess thats not true like that. can you explain why? because was far as i know there is a lexical environment for each function called which has a pointer to its outer environment and if a func does not find a var within its scope it searches within the outer environment. does it it find it not within but within its env. but within the outer (there can be a chain) its a closure. – Robin F. Mar 13 '17 at 22:20
  • 1
    @RobinF. By strict definition, It's a closure already when it does have the pointer to the outer environment, not when it uses this chain to lookup a variable. (That sounds like `function() { if (false) return global }` would not be a closure - and would make it an undecidable problem in general even) – Bergi Mar 13 '17 at 22:26
  • @Bergi makes sense. thanks. – Robin F. Mar 13 '17 at 22:27

0 Answers0