Skip to main content

Command Palette

Search for a command to run...

Understanding Closures: A Simple Guide

Published
โ€ข1 min read
Understanding Closures: A Simple Guide
K

Writing code, breaking things, then pretending it was a feature. ๐Ÿคก | Senior Software Engineer | Dreaming of Big Tech, a GDE badge, and a Koenigsegg. ๐Ÿš€

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

More from this blog

Code & Chaos

46 posts

Welcome to Code & Chaos ๐Ÿš€

I share thoughts on frontend dev, web performance, debugging nightmares, system design Stick around! ๐Ÿ˜ƒ