Skip to content
  • AI
  • Github

Scratch that

Bite sized bits

  • AI
  • Github
  • ⤫

Javascript Closure

Posted by Posted on
0

Introduction
In JavaScript, a closure is a function that has access to the variables and scope of its outer function, even after the outer function has returned. This allows the closure to retain its state and continue to operate, even after its outer function has finished executing.

Example
Here is an example of a closure in JavaScript:

Copy Code Copied! Use a different Browser

function outerFunction() {
let outerVariable = “Hello, world!”;

return function innerFunction() {
console.log(outerVariable);
};
}

let closure = outerFunction();
closure(); // logs “Hello, world!”

In the example above, the outerFunction defines a outerVariable variable and returns a innerFunction. The innerFunction has access to the outerVariable variable, even after the outerFunction has returned.

When the closure variable is assigned the return value of the outerFunction, it becomes a function that can access the outerVariable variable. When the closure function is called, it logs the outerVariable to the console.

Advantages of Closures
Closures have several advantages over other ways of retaining state in JavaScript:

Categories: Front-end, Javascript

Post navigation

Next Next post: Typescript basics
  • Algorithms
  • Front-end
  • Javascript
  • Philosophy
  • Project Management
  • Psychology
  • Science
  • Technology
  • Uncategorized
Copyright © 2025 - Scratch that // By - Deepak Anandrao