JAVASCRIPT CLOUSURES

JavaScript variables can belong to the local or global scope.
JS

They can be made local (private) with closures.

GLOBAL VARIABLES

A function can access all variables defined within the function, like this:

function myFunction() {
  let a = 4;
  return a * a;
}

But a function can also access variables defined outside the function, like this:

let a = 4;
function myFunction() {
  return a * a;
}

In the last example, a is a global variable. In a web page, global variables belong to the window object. Global variables can be used (and modified) by all scripts in the page (and window). In the first example, a is a local variable. A local variable can only be used within the function in which it is defined. It is hidden from other functions and other scripting code. Global and local variables with the same name are different variables. Changing one does not change the other. Variables created without a declaration keyword (var, let, or const) are always global, even if they are created within a function.

myFunction();

document.getElementById(“demo”).innerHTML = a * a;     //return 16

function myFunction() {
  a = 4;
}

LIFE CYCLE OF VARIABLES

Global variables are active until the page is deleted, such as when you switch to another page or close the window. Local variables are short-lived. They are created when the function is called and deleted when the function is finished.

JAVASCRIPT CLOSURES

When a function is invoked we know that a specific execution context is created for that function. In fact, if we invoke the same function five times, five separate execution contexts are created. Variables and internal functions are stored in memory. Once the code is finished, not only is the execution context removed, but the memory used to store those values is also freed. Values that are placed in memory so that instructions can be executed after execution are completed are removed from memory. When a function returns another function, the concept of closures comes into play. The inner function performs a closure on the outer execution context.

Copy to Clipboard

THE JAVASCRIPT LANGUAGE

THE JAVASCRIPT LANGUAGE

LINK TO THE CODE ON GITHUB

GITHUB