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?