DEV Community

Karthikeyan
Karthikeyan

Posted on

3 2 1 1 2

One Byte Explainer - Closures

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"

Enter fullscreen mode Exit fullscreen mode

Thank you for reading , See you in the next blog

final

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up