1

I am trying to dig deeper into javascript, and although I have found explanations on the differences between "var", "let", and "const" as well as explanations on ES6 "environment records" (declarative vs. object), I am still lost why the following code works the way it does when I type it into the Google Chrome Browser Console:

var a = 2;
let b = 4;

console.log(window.a); // 2
console.log(window.b); // undefined

console.log(a); // 2
console.log(b); // 4

If console.log(b) prints 4, but console.log(window.b) prints undefined, then what scope is b defined in?

I understand that when var is used outside of a function, it creates an undefined variable in the global scope. What I don't understand is what happens when let or const is used outside of a function as in the example above?

I assume based on other answers that this behavior has something to do with ES6 environment records, but when I read the reference book, it truly does not make sense to me.

Can someone explain this in slightly simpler terms than in that reference book?

Zach Gollwitzer
  • 2,114
  • 2
  • 16
  • 26
  • 1
    I think the dup is pretty much a match, but to elaborate a little, essentially there is the global object scope, and the global lexical scope, and `let` creates a binding attached to the global lexical scope, and `window` only accesses the global object scope. The global object scope is the outer-most, and the global lexical is the single scope nested inside it, and all other scopes for modules and functions and things end up inside that one. – loganfsmyth Jul 03 '19 at 21:35
  • For an answer I believe you can look at the specification under `Runtime Semantics: EvalDeclarationInstantation`(https://tc39.es/ecma262/#sec-evaldeclarationinstantiation) specifically 5.a.i.2 which states *"NOTE: eval will not create a global var declaration that would be shadowed by a global lexical declaration."* – zfrisch Jul 03 '19 at 21:43

0 Answers0