0

I've been studying closures and callbacks, for the last hours, and I wrote this function to better understand the concepts of closures. I know that in this example, closure is not happening because callback is called inside the same execution context as function one().

function one(callback) {
   let a = 1;
   let b = 2;

   callback()
}


one(function () {
   console.log(a);
});
// Uncaught ReferenceError: a is not defined

Even though the callback is executed in the same execution context as function one(), why can't I access a with the callback? Is it because let being scope limited and therefore the callback cant access it once it reaches to it's execution? Shouldn't the callback go down the scope chain and find a?

Thank you

Tiago Ruivo
  • 183
  • 1
  • 9
  • Javascript has *lexical* scope. If a variable is declared in a block, it will be accessible from within that block, and within any descendant blocks, and nowhere else. Here, `a` is not in an ancestor block of the `one` call, so it's not accessible from there. – CertainPerformance Nov 22 '19 at 20:06
  • So we could say that callback() and a are at the same child level, therefore when I run the callback() it goes down in the chain scope doesn't find a and returns the error? – Tiago Ruivo Nov 22 '19 at 20:23

0 Answers0