let scope

var id = 2;
function x() {
  console.log(id);  //reference error 
  let id = 3;
  console.log(id); 
}
x();

雖然let引入block scope,避免了var的variable hoisting,但是須注意

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

let bindings are created at the top of the (block) scope containing the declaration, commonly referred to as "hoisting". Unlike variables declared with var, which will start with the value undefined, let variables are not initialized until their definition is evaluated. Accessing the variable before the initialization results in a ReferenceError. The variable is in a "temporal dead zone" from the start of the block until the initialization is processed.

所以上面的id會引發reference error
但是比較var範例

var id = 2;
function x() {
  console.log(id); 
  //undefined,因為下面定義的variable hoisting
  var id = 3;
  console.log(id); 
}
x();
This entry was posted in nodejs. Bookmark the permalink.

Leave a Reply