DEV Community

Madhan Raj
Madhan Raj

Posted on

JavaScript Closures

JavaScript variables can belong to:
The local scope
The global scope

Global variables can be made local (private) with closures.

Closures make it possible for a function to have "private" variables.

A closure is created when a function remembers the variables from its outer scope, even after the outer function has finished executing.

Closures are an advanced topic.

Make sure you understand JavaScript functions and scope first.

JavaScript Functions

JavaScript Scope

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;
}
Enter fullscreen mode Exit fullscreen mode

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;
}

Enter fullscreen mode Exit fullscreen mode

In a web page, global variables belong to the page.

Global variables can be used (or changed) by all scripts in the page.

A local variable can only be used inside the function where it is defined. It is private and hidden from other functions and other scripting code.

Global and local variables with the same name are different variables. Modifying one, does not modify the other.

Undeclared variables (created without a keyword var, let, const), are always global, even if they are created inside a function.
Example

The variable a is a global variable because it is undeclared:

function myFunction() {
  a = 4;
}
Enter fullscreen mode Exit fullscreen mode

REFERENCE
https://www.w3schools.com/js/js_function_closures.asp

Top comments (0)