JavaScript Closures
JavaScript variables can belong to:
The local scope or The global scope
Global variables can be made local (private) with closures.
Closures makes it possible for a function to have "private" variables.
Local Variables
A local variable is a "private" variable defined inside a function.
A function can access all variables in the local scope.
Example
a is a local variable defined inside the function:
function myFunction() {
let a = 4;
return a * a;
}
Global Variables
A global variable is a "public" variable defined outside a function.
A function can access all variables in the global scope:
Example
a is global variable defined outside the function:
let a = 4;
function myFunction() {
return a * a;
}
Top comments (0)