Skip to content

Instantly share code, notes, and snippets.

@xiaoyunyang
Last active October 2, 2021 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xiaoyunyang/95ab6b8d2a1f6a9bb7f9ccf859472492 to your computer and use it in GitHub Desktop.
Save xiaoyunyang/95ab6b8d2a1f6a9bb7f9ccf859472492 to your computer and use it in GitHub Desktop.
Closure Example - Recursion
var incrementUntil = function(max) { 
if(num >= max) return num 
num++
incrementUntil(max)
}
 
var num = 0
incrementUntil(3)
num //> 3
@xiaoyunyang
Copy link
Author

xiaoyunyang commented Jan 25, 2018

Let’s try a couple of things based on the function we created from the previous example:

num = 0
var myFun = function() { 
 incrementUntil(3)
 return num 
}
myFun() //> 3
num //> 3

So far so good…

num = 0
var myFun2 = function() { 
 var num = -1
 incrementUntil(3)
 return num 
}
myFun2() //> -1 …….Why?
num //> 3

…Uh oh what happened?

Observation: closure is tied to the scope in which it is first created, not where it is called.

Although incrementUntil is being executed to myFun2, it didn't modify the num in myFun2's scope because incrementUntil only recognizes the num that was inside of its parent's scope when it was first created. It doesn't recognize the num inside of the caller, myFun2 because it doesn't maintain a closured reference to its caller's scope.

How do we fix myFun2?

var myFun2 = function() { 
   var num = -1
	
   function incrementUntil(max) { 
      if(num >= max) 
         return num 
	 num++
	 incrementUntil(max)
   }
   
   incrementUntil(3)
   return num 
}
	
myFun2() //> 3

@ArtemHas
Copy link

ArtemHas commented Oct 2, 2021

ok

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment