GithubHelp home page GithubHelp logo

closure's Introduction

Closure

Defnition: "A closure is a function having access to the parent scope even after the parent function has closed"

Example:

let x = 1; //global scope
const parentFunction = () => {
    //parent scope 
    let y = 2;
    console.log(x);
    console.log(y);
    const childFunction = () => {
        //local scope
        console.log(x += 5);
        console.log(y += 1);  
    }
    return childFunction;
}
const result = parentFunction();
console.log(result); 
result(); /* calling child function. it will access y in parent function 
even the parent function has already been called and closed. child function 
still has access to the scope and that makes y private variable that
only child function has access to */

Output:

  1
  2
  ()=>{
    //local scope
        console.log(x += 5);
        console.log(y += 1);
  }
  6
  3

Points to Remember:

- controls the variable that are being shared with the nested function
- the inner function has access to the variables in its local scope, parent function and in the global scope 
- In Js, we can use private variables and methods using closure
- helps in maintaining the state between each function calls without using a global variable.
- closure is created at function definition not at function invocation.

closure's People

Contributors

kirthi2005 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.