Understanding Closures: A Simple Guide

ยท

1 min read

Hello ๐Ÿ‘‹

Let's start with Closures

One-Byte Explainer:

Imagine a magic box! Put your favourite toy inside, close it, & give it to a friend. Even though you can't see it, your friend can open it and play!

Demystifying JS: Closures in action

Closures are like backpack the inner-functions carry when they exit the outerfunctions , even after the outer function's execution is destroyed.

  1. Function Inside a Function: You have a function inside another function.

  2. Access to Outer Variables: The inner function can access variables from the outer function.

  3. Retain Variables: Even after the outer function finishes, the inner function keeps the outer variables.

Example :


function outer() {
    let outerscope = "I am outer scope";

    function inner() { 
        let innerScope = "I am in inner scope";
        console.log(`${outerscope} and ${innerScope}`);
    }

    return inner;
}

const calling = outer();
calling(); // Output: "I am outer scope and I am in inner scope"

Thank you for reading , See you in the next blog

final