JavaScript variables can belong to the local or global scope.
Global variables can be made local (private) with closures.
Global variable
A function can access all variable defined inside the function like this:-
function calculateNum() {
let a = 4;
return a * a
}
But a function can also access the variable outside of the function like this:-
let i = 4;
function calculateNum() {
return i * i
}
in the above example a is a global variable.
In a webpage global variable belong to the window object.
In the first example, a is a local variable.
A local variable can only used inside the function where it is defined. it is hidden from other function they can't use them.
Global and local variables with the same name are different variables. Modifying one, does not modify the other.
Closures Example
const add = (function () {
let counter = 0;
return function () {counter += 1; return counter}
})();
add();
add();
add();
Example explained
a variable add is assigned to the returning value of a self invoking function
a self invoking function only runs a once. it's sets the counter set to(0) and return a function expression
This way add becomes a function. The "wonderful" part is that it can access the counter in the parent scope.
This is called a JavaScript closure. It makes it possible for a function to have "private" variables.
The counter is protected by the scope of the anonymous function, and can only be changed using the add function.
Top comments (0)