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

The difference between let and var in JS

autoload
Release: 2021-03-31 16:42:14
Original
2689 people have browsed it

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
Copy after login
  • 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;
Copy after login

  • 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;
Copy after login
  • 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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template