Last active
October 2, 2021 15:40
-
-
Save xiaoyunyang/95ab6b8d2a1f6a9bb7f9ccf859472492 to your computer and use it in GitHub Desktop.
Closure Example - Recursion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var incrementUntil = function(max) { | |
if(num >= max) return num | |
num++ | |
incrementUntil(max) | |
} | |
var num = 0 | |
incrementUntil(3) | |
num //> 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Let’s try a couple of things based on the function we created from the previous example:
So far so good…
…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 tomyFun2
, it didn't modify thenum
inmyFun2
's scope becauseincrementUntil
only recognizes thenum
that was inside of its parent's scope when it was first created. It doesn't recognize thenum
inside of the caller,myFun2
because it doesn't maintain a closured reference to its caller's scope.How do we fix
myFun2
?