To understand JavaScript Closures you must first understand, the JavaScript Variable Scope. WATCH VIDEO BELLOW
What is a closure ? a closure is a function.
When you create a function, and this function has an inner function, the inner function is a CLOSURE.
EXAMPLE :
|
let globalVariable =
"global";
|
|
|
function main(){
|
|
|
let
mainlocalVariable = "local";
|
|
|
function
inside(){
|
|
|
let
insideLocalVariable = "local";
|
|
|
}
|
|
|
}
|
|
|
|
|
Our main() function here, has an inner function: inside().
inside() is a closure.
The inside() function, our closure, has access to insideLocalVariable, the variable in its own scope (variables defined between its curly brackets), also it has access to the outer function's (mainFunction) variables, in this case, mainLocalVariable, and also it has access to globalVariable.
Here are some closure's characteristics :
a closure has access to the outer function's variable, even when the outer function returns, which means, that the closure do not store the outer variable value, instead, it stores the variable reference.
Here is a tutorial I made on JavaScript Closures, I hope it will help you, understand more about them.
first I will talk about JavaScript scope, and JavaScript nested functions (inner functions), the life of the variables, both global and local variables, and we will see how a function closure and it's environment are created. and what is a private variable.
Tags:
JavaScript