Hazem Hagrass

Software Engineer

Technical Lead

Hazem Hagrass
Hazem Hagrass
Hazem Hagrass
Hazem Hagrass

Software Engineer

Technical Lead

Blog Post

How is Closure Working With Let in JS?

June 24, 2017 Web
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 the function keyword is used inside another function and has 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 its parent scope and can access all parent variables and functions.

Briefly running saga[0]() in the example below will lead 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();
Write a comment