var let difference

In JavaScript, both var and let are keywords used to declare variables. However, they differ in scope, variable hoisting, repeated declarations, etc.

Following are the main differences between var and let −

Scope: Variables declared with var have function scope or global scope, while variables declared with let have block scope.

  • The variables declared by var can be accessed inside and outside the function, but in the block-level scope (such as if statement, for statement), the variables declared by them can also be accessed.
function test() {
    
    
  var a = 10;
  if (true) {
    
    
    var b = 20;
    console.log(a); // 输出: 10
  }
  console.log(b); // 输出: 20
}
  • Variables declared by let can only be accessed in the block-level scope and cannot be accessed outside the block-level scope.
function test() {
    
    
  let a = 10;
  if (true) {
    
    
    let b = 20;
    console.log(a); // 输出: 10
    console.log(b); // 输出: 20
  }
  console.log(b); // 抛出ReferenceError异常: b未定义
}

Variable promotion: Variables declared by var have a variable promotion phenomenon, and variables declared inside and outside the function will be promoted to the top of the scope. The variables declared by let do not have variable promotion, and can only be used after they are declared.

  • Variables declared by var have variable promotion:
function test() {
    
    
  console.log(a); // 输出: undefined
  var a = 10;
}
  • Variables declared by let do not have variable promotion:
function test() {
    
    
  console.log(a); // 抛出ReferenceError异常: a未定义
  let a = 10;
}

Repeated declaration: Variables declared by var can be declared repeatedly in the same scope, while variables declared by let cannot be declared repeatedly in the same block-level scope.

  • Variables declared with var can be declared repeatedly in the same scope:
function test() {
    
    
  var a = 10;
  var a = 20;
  console.log(a); // 输出: 20
}
  • Variables declared by let cannot be declared repeatedly in the same block-level scope:
function test() {
    
    
  let a = 10;
  let a = 20; // 抛出SyntaxError异常: 标识符'a'已经声明过了
}

To sum up, let is superior to var in many cases, because it avoids many common problems, such as variable hoisting and double declaration. Therefore, it is recommended to use let to declare variables in modern JavaScript, unless specific var behavior is required.

Guess you like

Origin blog.csdn.net/weixin_47287832/article/details/129833504