Closure in JavaScript – Little-Known Facts and Why They Matter | DataTrained

Chandrakishor Gupta Avatar

Introduction

A Closure can be succinctly described as a collection of functions and their associated lexical environment. Upon the creation of a function, a Closure is automatically generated. This article will serve as an in-depth exploration of the subject of Closure in JavaScript, covering topics such as scopes, lexical scopes, scope chains, and the application of Closure in JavaScript.

What are Scopes?

What are Scopes?

In JavaScript, the scope defines the region of code in which a given variable is accessible. To provide an illustrative example, consider the following:

const name = “Datatrained”;

console.log(name); // Outputs: Datatrained

if (true) { 

  let superhero = “Datatrained”; 

  console.log(Datatrained); // Outputs: Datatrained

console.log(superhero); // Throws ReferenceError

In JavaScript, there are various types of scopes,

  • Block Scope
  • Global Scope
  • Functional Scope.

Block Scope

The let and const keywords enable variables to be bound within a specific code block or set of curly braces “{}”. It should be noted that the var keyword does not support block-level scoping.

{

  let name1 = “Datatrained”; // name1 defined in local scope

  console.log(name1); // Outputs “Datatrained”

}

{

  var newName = “Datatrained”; // newName not defined in local scope as ‘var’ is used instead of ‘let’ or ‘const’

  console.log(newName); // Outputs “Datatrained”

}

console.log(name1); // Produces a ReferenceError, as name1 is not accessible outside the block scope where it was declared. 

console.log(newName); // Outputs “Datatrained”

Global Scope

A variable that is accessible from any part of the program is referred to as existing in the global scope, which is consistent with its name.

Example

let name = “Datatrained”;

function mainFunction() {

  console.log(name);

}

mainFunction(); // Outputs “Datatrained” to the console

console.log(name); // Outputs “Datatrained” to the console

The variable name is accessible in both the main Function and outside of it, enabling its access from any point within the code. This indicates that the name exists in a global scope. To know more about data science course in Kerala

Function Scope or Local Scope

Function Scope or Local Scope

A variable declared within a function is confined to the functional scope and can only be accessed from within the function; Closure in JavaScript, it cannot be used in any other context.

Example

const main = () => {

  const newName = ‘Datatrained’; // Variable declared within the function scope 

  console.log(newName); 

}

main();

// Attempting to access the variable outside of the function’s scope  

console.log(newName); // ReferenceError

The most imperative aspect of grasping closures is Lexical Scope.

Lexical Scoping 

Lexical scope refers to a function’s ability to access variables from its parent scope. We refer to the parent function’s lexically binding of the child function as “lexical binding”.

function foo() {

  let b = 1;

  function inner() {

    return b;

  }

  return inner;

}

let getFuncInner = foo();

console.log(getFuncInner());

console.log(getFuncInner());

console.log(getFuncInner());

Closure in JAVAScript

A closure is a combination of a function and its associated lexical environment, providing access to an outer function’s scope from an inner function. Closure in JavaScript, In JavaScript, closures are generated upon the creation of every function. Click here to know about data science in India

In order to gain a comprehensive understanding of closure concepts, it is necessary to be familiar with two related ideas:

  • Nested Function
  • Returning a function

JavaScript Nested Function

In the programming language JavaScript, a function can contain an additional function, which is known as a nested function.

 As an illustration,

// Nested Function Example

// Outer Function

function greet(name) {

    // Inner Function

    function displayName() {

        console.log(`DataTrained${name}`);

    }

    // Invoking Inner Function

    displayName();

}

// Invoking Outer Function

greet(‘TRAINED’); // Datatrained

The program contains a greet() function, which encapsulates the displayName() function.

Returning a Function

Within JavaScript, it is possible to return a function from within a function. As an illustration,

function greet(name) {

    const displayName = () => console.log(`DataTrained${name}`);

    // returning a function

    return displayName;

}

const g1 = greet(‘Datatrained’);

console.log(g1); // returns the function definition

g1(); // calling the function

In the above program, the greet() function is returning the displayName function definition.

Scope Chain

In JavaScript, the concept of a hierarchical chain scope is referred to as the Scope Chain, whereby a scope has access to its outer environment or parent scope, which in turn has access to its own outer environment.

Closure and Scope Chain

Closure and Scope Chain

Having acquired an understanding of scope, scope chains, and closures, it is now possible to examine the relationship between scope chaining and closures in JavaScript. In terms of scope chaining, we know that the JavaScript interpreter will traverse the chain of scopes to locate a variable, beginning with the local scope and progressing up through its parent scopes until it reaches the global level. The same is true of closures; this can be illustrated with an example.

let globalName = “Datatrained”; // Declared in the Global Scope

function outerFunction() {

  let outerName = “Datatrained”; // Declared in the scope of OuterFunction

  function innerFunction () {

      let innerName = “Datatrained”; // Declared in the scope of InnerFunction

      return function () {

        localName = “Datatrained”; // Declared in the local scope of the function

        console.log(localName);

      }

  }

  return innerFunction();

}

const fn = outerFunction();

fn(); // Prints Datatrained

JavaScript Closures

In JavaScript, closure allows for the preservation of an outer function’s scope within an inner function, even after the outer function has returned. As an illustration,

// JavaScript Closure Example

// Outer Function

function greet() {

    // Variable Defined Outside Inner Function

    let
name = ‘Datatrained’;

    // Inner Function

    function displayName() {

        // Accessing Name Variable

        return `Datatrained${name}`;

       }

    return displayName;

}

const g1 = greet();  // Invoking greet() returns the displayName function definition. 

console.log(g1());    // Invoking g1() returns the value of the name variable.

How to Move Forward With Closure in JavaScript

How to Move Forward With Closure in JavaScript?

Gaining an understanding of closures requires a practical approach. As the concept can be complex, it is beneficial to explore and create closures in different scenarios to acquire a clear comprehension of their various uses. Through this method, one can identify closures and gain greater proficiency in their implementation in order to accomplish tasks that would otherwise be more arduous. Practicing closures is thus instrumental in consolidating knowledge of the subject.

Conclusion

Closure in JavaScript is a ubiquitous feature, yet unfamiliar to many developers. Mastering closures can be challenging, however with time and practice one can become increasingly proficient. A closure in JavaScript is an inner function that has access to the variables of the outer (enclosing) function via the scope chain. Closures are created when a function is declared.

Related blogs:-

What are Data Types in JavaScript

Top 6 Benefits of Online JavaScript Compiler

Top 35+ TypeScript Interview Questions

Frequently Asked Questions

Why use closure in JavaScript?

Closure in JavaScript is a form of lexical scoping that maintains variables from the external scope of a function within the internal scope of that function. Lexical scoping is a mechanism used to determine the extent to which a variable is accessible, based on its location relative to other code in the source file.

Closure in JavaScript is commonly utilized to provide object data privacy, in addition to for event handlers and callback functions. Furthermore, they are regularly applied in partial applications, currying, and other functional programming patterns.

The closure is attained when we are content that the puzzle has been successfully assembled, that the solutions have been identified, and consequently, progression can occur. People tend to seek closure primarily when the conclusion of the situation holds personal value and import.

A closure is a combination of a lexically scoped function, along with its associated environment of variables, which enables access to the outer function’s scope from within the inner function.

Closure in JavaScript refers to a feature wherein an inner function has access to the variables of the outer (enclosing) function, thus forming a scope chain. Closures are created in conjunction with the definition of a function and use lexical scoping to maintain the environment that holds both the current and outer scope variables.

Tagged in :

More Articles & Posts

UNLOCK THE PATH TO SUCCESS

We will help you achieve your goal. Just fill in your details, and we'll reach out to provide guidance and support.