how is closure working with let in js?

Function Keyword

I believe that in javaScript the interpreter is understanding that you are creating a closure if function keyword is used inside another function and been returned.

in most other common languages, after a function returns, all the local variables are no longer accessible because the context is destroyed, however in JavaScript, if a function is declared within another function, then all local variables can remain accessible after returning from the function you called. In simple words, the inner function will run in it’s parent scope and can access all parents variables and function.

Briefly running saga[0]() in the example below will leads to ‘BoyDeedRat‘ as an output.


function aHero() {
  return 'Boy'
}
function aFoil() {
  return 'Rat'
}
function aDeed() {
  return 'Deed'
}
let sagas = [];
let hero = aHero();
let newSaga = function () {
  let foil = aFoil();
  sagas.push(function () {
    let deed = aDeed();
    console.log(hero + deed + foil)
  });
}
newSaga();
sagas[0]();
sagas[0]();
newSaga();

 

Leave a Reply

Your email address will not be published. Required fields are marked *

© 2019 Hazem Hagrass | ScrollMe by AccessPress Themes