Manoj Kumar Duraisamy
What is closure in JavaScript?

What is closure in JavaScript?

By Manoj Kumar Duraisamy in JavaScript on Jun 20 2023
  • Mayooran Navamany
    Jun, 2023 24

    A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the local environment). In other words, a closure gives you access to an outer function’s scope from an inner function.

    JavaScript variables can belong to the local or global scope.
    Global variables can be made local (private) with closures.

    Global Variables
    A function can access all variables defined inside the function,

    1. function myFunction() {
    2. let a = 4;
    3. return a * a;
    4. }

    But a function can also access variables defined outside the function,

    1. let a = 4;
    2. function myFunction() {
    3. return a * a;
    4. }

    In JavaScript, closures are created every time a function is created, at function creation time.

    1. function makeFunc() {
    2. const name = "C-Sharpcorner";
    3. function displayName() {
    4. console.log(name);
    5. }
    6. return displayName;
    7. }
    8. const myFunc = makeFunc();
    9. myFunc();

    • 0
  • Vijay K
    Jun, 2023 20

    ..

    • 0
  • Vijay K
    Jun, 2023 20

    Closure gives access to outer function scope from on inner function.
    Closure Function is combination of function bundles together(EnClosed) with refernce to its Surrounding State.
    Closure create every time the function is created,at function creation time.
    Ex:
    function init(){
    var name =”Vijay”;
    function disp(){
    console.log(“Closure Function Value is:” +name);
    }
    disp();
    }
    init();

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS