JavaScript Closures

A closure is a combination of a function bundled together (enclosed) with references to its surrounding state (the lexical scope).

Lexical scoping

The stance of a variable asserted in the source code denotes its scope in syntactic figuring.

For example:

let name = 'John';

function greeting() {

    let message = 'Hi';

    console.log(message + ' '+ name);


In this example:

  • The variable name is a global variable. It can be accessed from wherever, including the greetings() function.
  • The variable message is a local variable that is accessible only within the greeting() function.

If you try to access the message variable outside the greeting() function, you will get an error.

As a result, the JavaScript machine produces use of the scope to handle variable mobility. The scopes can be clustered as per syntactic scoping, and the internal function can access the variables asserted in its external scope.

For example:

function greeting() {

    let message = 'Hi';

    function sayHi() {







The greetings() function declares a local variable called message as well as a feature called sayHi (). The sayHi() function is an inner function that is only accessible well within skin of the greetings() function. The sayHi() function has full rights to the variables of the outer function, such as the greetings() function’s memo variable.

Inside the greeting() function, we call the sayHi() function to display the message Hi.


The closure allows you to access the scope of an external function from an internal function. Closures are formed in JavaScript each moment a function is generated, at function creation time.

<!DOCTYPE html>



<h2>JavaScript Closures</h2>

<p>Counting with a local variable.</p>

<button type="button" onclick="myFunction()">Count!</button>

<p id="demo">0</p>


const add = (function () {

  let counter = 0;

  return function () {counter += 1; return counter;}


function myFunction(){

  document.getElementById("demo").innerHTML = add();





Example Explained

A self-supplicating function’s returns value is assigned to the variable add.

The self-supplicating function only runs once. It reverts a function appearance and resets the table to zero (0).

This way add becomes a function. The “marvelous” part is that one can gain entry to the parent scope’s table.

This is called a JavaScript closure. It makes it possible for a function to have “private” variables.

The unidentified function’s scope protects the counter, and it can only be changed with the add function.


  • Lexical scoping defines how the JavaScript engine determines where a variable is available based on its location in the code.
  • A closure is a feature with the ability to recall variables in the external scope.

Leave a Reply