Created
November 24, 2019 05:55
-
-
Save bhaveshdaswani93/b3d2d0bcff48c19b360950edef8c7e52 to your computer and use it in GitHub Desktop.
This is an example to understand closure
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
function a() { | |
let grandFather = 'grandpa'; | |
return funciton b() { | |
let father = 'father'; | |
return function c() { | |
let son = 'son'; | |
return `${grandFather} > ${father} > ${son}`; | |
} | |
} | |
} | |
const funcAResult = a() // return b function | |
// by now 'a' funciton will removed from call stack but grandFather variable will not be removed by garbage collection as it is refrenced by one of child function | |
const funcBResult = funcAResult() // returnc function c | |
// by now 'b' funciton will removed from call stack but father variable will not be removed by garbage collection as it is refrenced by one of child function | |
funcBResult() // will print 'grandpa > father > son' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment