DEV Community

Cover image for JavaScript : Closures (English/Hindi)
Dharmik Dholu
Dharmik Dholu

Posted on

JavaScript : Closures (English/Hindi)

English

A closure in JavaScript is a concept where a function retains access to the variables from its containing (enclosing) function, even after that enclosing function has finished executing. This means that a function "closes over" the variables it needs, keeping them alive beyond their original scope.

function outerFunction() {
  let outerVariable = "I'm from outer function";

  function innerFunction() {
    console.log(outerVariable); // inner function can access outerVariable
  }

  return innerFunction;
}

const closureExample = outerFunction(); // closureExample now holds the innerFunction

closureExample(); // Outputs: "I'm from outer function"

Enter fullscreen mode Exit fullscreen mode

Hindi

JavaScript mein ek closure ek aisa concept hai jahan ek function apne enclosing function ke variables tak ka access rakhta hai, us enclosing function ka execution khatam hone ke baad bhi. Iska matlab hai ki ek function "closes over" (apni baahar ke) variables ko, aur unhe unke asal scope se bahar rakh deta hai.

function outerFunction() {
  let outerVariable = "Main bahar waale function se hoon";

  function innerFunction() {
    console.log(outerVariable); // andar waala function outerVariable tak ka access kar sakta hai
  }

  return innerFunction;
}

const closureExample = outerFunction(); // closureExample ab innerFunction ko hold karta hai

closureExample(); // Output: "Main bahar waale function se hoon"

Enter fullscreen mode Exit fullscreen mode

Top comments (0)