Home >Web Front-end >JS Tutorial >The difference between let and var in JS

The difference between let and var in JS

autoload
autoloadOriginal
2021-03-31 16:42:142685browse

The difference between let and var in JS

1. Differences in scope:

{
  let a = 10;
  var b = 1;
 }
  a // ReferenceError: a is not defined.
  b // 1
  • varThe keyword is a global variable or a function variable

  • letThe keyword is a block scope

##2. The difference between defining and using variables:

// var 的情况
console.log(foo); // 输出undefined
var foo = 2;
 
// let 的情况
console.log(bar); // 报错ReferenceError
let bar = 2;

  • let must be defined first and then used,

  • var can be used first and then declared. When using an undefined variable, its value is undefined

##3 .Differences in repeated declarations:

   var a;
   var a;

   
   let b;
   let b;

  • var

    The repeated declaration of keywords is correct;

  • let

    Repeat keyword declaration error; Uncaught SyntaxError: Identifier 'b' has already been declared

  • Recommendation: "
2021 js interview questions and answers ( Large summary)

The above is the detailed content of The difference between let and var in JS. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn