0

The book says:

No matter where a function is invoked from, or even how it is invoked, its lexical scope is only defined by where the function was declared.

And here is an example that proves it:

let a = "1";

function test() {
  console.log(a);
}

function newZone() {
  let a = "2";
  test();
}

newZone();

But in this case the Lexical Scope is defined at the moment the function is called:

let a = 1;

function test() {
  console.log(a, b);
}

test(); // error

let b = 10;

test(); // 1,10

Help me understand when Lexical Scope is defined

Andy
  • 61,948
  • 13
  • 68
  • 95
turok 9661
  • 51
  • 3
  • It's still lexical scode. The declaration of `b` is [hoisted](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting) and you're trying to access it in the temporal dead zone: https://stackoverflow.com/questions/33198849/what-is-the-temporal-dead-zone – jabaa Aug 27 '21 at 08:09
  • https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var – ksav Aug 27 '21 at 08:09
  • `let` variables are not initialized until their definition is evaluated. Accessing them before the initialization results in a `ReferenceError`. Variable said to be in "temporal dead zone" from the start of the block until the initialization is processed. – ksav Aug 27 '21 at 08:10
  • Nothing changes in terms of the function’s lexical scope. You’re merely tripping over further restrictions. – deceze Aug 27 '21 at 08:11
  • [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask): _"Write a title that summarizes the specific problem"_ – Andreas Aug 27 '21 at 08:12
  • @ksav Why doesn't the book say that, then? – turok 9661 Aug 27 '21 at 08:12
  • I guess you would need to ask the author – ksav Aug 27 '21 at 08:13
  • 1
    @turok9661 I suppose because it's in a different chapter. `let` and `const` aren't really related to lexical scoping of functions. – VLAZ Aug 27 '21 at 08:13
  • 1
    The book (and its author) is available on [github](https://github.com/getify/You-Dont-Know-JS). The author also talks about a similar example in this [issue](https://github.com/getify/You-Dont-Know-JS/issues/1132) – Andreas Aug 27 '21 at 08:27

0 Answers0