What are closures?

What are closures?

What are closures

A closure is the combination of a function and the lexical environment within which that function was declared. i.e, It is an inner function that has access to the outer or enclosing function’s variables. The closure has three scope chains

  1. Own scope where variables defined between its curly brackets
  2. Outer function’s variables
  3. Global variables

Let's take an example of closure concept,

function Welcome(name) {
  var greetingInfo = function (message) {
    console.log(message + " " + name);
  };
  return greetingInfo;
}
var myFunction = Welcome("John");
myFunction("Welcome "); //Output: Welcome John
myFunction("Hello Mr."); //output: Hello Mr.John        

As per the above code, the inner function(i.e, greetingInfo) has access to the variables in the outer function scope(i.e, Welcome) even after the outer function has returned.

要查看或添加评论,请登录

Jayesh Chauhan的更多文章

  • ?? Demystifying JS vs. JSX ??

    ?? Demystifying JS vs. JSX ??

    Understanding Their Roles in React Development In the vast realm of web development, JavaScript (JS) and JSX play…

  • Which one is best React JS, Next JS, React Native?

    Which one is best React JS, Next JS, React Native?

    ReactJS, Next.js, and React Native are all frameworks built on top of the React library, which is developed and…

    1 条评论
  • Variable Declaration in JavaScript

    Variable Declaration in JavaScript

    Declare JavaScript Variables In computer science, data is anything that is meaningful to the computer. JavaScript…

社区洞察

其他会员也浏览了