Skip to content

Closure

sjagoori edited this page Jun 24, 2020 · 5 revisions

Closure

The concept

The concept of closures allows code to be declared in a function and be readable in a child-function (see hoisting). The child function for example read the declared variables from the parent function- or even the global variables whereas parent functions are unable to read variables declared in child functions; it works only outwards.

Code example

function init() {
  let name = 'Mozilla'; // name is a local variable created by init
  function displayName() { // displayName() is the inner function, a closure
    console.log(name); // use variable declared in the parent function
    let aaa ="aaa"
  }
  displayName();
  console.log(aaa) // cant see in child parent
}
init();

Source

Closures. (2020, May 31). MDN Web Docs. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

Clone this wiki locally