Skip to content

Instantly share code, notes, and snippets.

@khzaw
Created June 10, 2020 02:17
Show Gist options
  • Save khzaw/fee2c0e6f260cafdd5815e2ef0718e38 to your computer and use it in GitHub Desktop.
Save khzaw/fee2c0e6f260cafdd5815e2ef0718e38 to your computer and use it in GitHub Desktop.
Closure exmaple
function outerFunc() {
// the outer scope
let outerVar = 'I am outside!';
function innerFunc() {
console.log(outerVar); // -> I am outside!
}
innerFunc();
}
outerFunc();
// Scopes can be nested
// The variables of the outer scope are accessible inside the inner scope
// How does JavaScript understand that `outerVar` inside `innerFunc()` corresponds to the variable `outerVar` of `outerFunc()`?
// It's because JavaScript implements a scoping mechanism named lexical scoping (or static scoping). Lexical scoping means that the accessibility of variables is determined
// by the position of the variables in the source code inside the nesting scopes.
// The lexical scoping means that insider the inner scope you can access variables of its outer scopes.
// It's called lexical(or static) becuase the engine determins (at lexing time) the nesting of scopes just by looking at the source code, without executing it.
function outerFunc() {
let outerVar = 'I am outside';
function innerFunc() {
console.log(outerVar); // -> 'I am outside!'
}
return innerFunc;
}
const myInnerFunc = outerFunc();
myInnerFunc();
// innerFunc() is executed outside of its lexical scope. And it still has access to `outerVar` from its lexical scope. `innerFunc()` closes over (captures, remebers) the variable `outerVar` from its lexical scope.
/*
* Examples
*
*/
// Event handler
let countClicked = 0;
myButton.addEventListener('click', function handleClick() {
countClicked++;
myText.innerText = 'You clicked ${countClicked} times`;
});
// handleClick() is executed somewhere inside of the DOM code. The execution happens far from the place of definition. But being a closure, handleClick() captures countClicked from the lexical scope and updates it when a click happens. Even more, myText is captured too.
// Callbacks
const message = 'Hello, world!';
setTimeout(function callback() {
console.log(message);
}, 1000);
// The `callback` is a closure because it captures the variable `message`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment