Skip to content

Instantly share code, notes, and snippets.

@bhaveshdaswani93
Created November 24, 2019 05:55
Show Gist options
  • Save bhaveshdaswani93/b3d2d0bcff48c19b360950edef8c7e52 to your computer and use it in GitHub Desktop.
Save bhaveshdaswani93/b3d2d0bcff48c19b360950edef8c7e52 to your computer and use it in GitHub Desktop.
This is an example to understand closure
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