4

Consider the code below which I am running in my chrome browser console:

var x = "hello";

let foo =  function(){
  console.log("hi");
};

console.log(x); // hello
console.log(foo()); //hi

console.log(window.x); // hello
console.log(window.foo()); // Error

If I had used var foo =... instead of let foo = .. then this would have worked. Why ?

Number945
  • 4,631
  • 8
  • 45
  • 83

1 Answers1

4

This is by design:

let allows you to declare variables that are limited to a scope of a block statement, or expression on which it is used, unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope. The other difference between var and let is that the latter is initialized to a value only when a parser evaluates it (see below).

Just like const the let does not create properties of the window object when declared globally (in the top-most scope).

mickl
  • 48,568
  • 9
  • 60
  • 89