📜  let和var关键字之间的区别

📅  最后修改于: 2021-01-11 12:21:40             🧑  作者: Mango

let和var关键字之间的区别

var关键字

var语句用于在JavaScript中声明变量。在整个程序中都定义了使用var关键字声明的变量。

var greeter = "hey hi";
var times = 5;
if (times > 3) {
   var greeter = "Say Hello JavaTpoint"; 
}
console.log(greeter) //Output: Say Hello JavaTpoint

输出:

让关键字

let语句用于在TypeScript中声明局部变量。它与var关键字相似,但是与var关键字相比,它在范围界定方面有一些限制。 let关键字可以增强我们的代码可读性,并减少编程错误的机会。用let关键字声明的变量仅限于块作用域。

注意:var和let之间的主要区别不在于语法,而在于语义。

let greeter = "hey hi";
let times = 5;
if (times > 3) {
   let hello = "Say Hello JavaTpoint"; 
   console.log(hello) // Output: Say Hello JavaTpoint
}
console.log(hello) // Compile error: greeter is not defined

输出:

上面的代码段引发错误,因为未全局定义变量“ hello”。

Var与让关键字

SN var let
1. The var keyword was introduced with JavaScript. The let keyword was added in ES6 (ES 2015) version of JavaScript.
2. It has global scope. It is limited to block scope.
3. It can be declared globally and can be accessed globally. It can be declared globally but cannot be accessed globally.
4. Variable declared with var keyword can be re-declared and updated in the same scope.
Example:
function varGreeter(){
  var a = 10;        
  var a = 20; //a is replaced
  console.log(a);
}
varGreeter();
Variable declared with let keyword can be updated but not re-declared.
Example:
function varGreeter(){
  let a = 10;        
 let a = 20; //SyntaxError: 
 //Identifier 'a' has already been declared
  console.log(a);
}
varGreeter();
5. It is hoisted.
Example:
{
  console.log(c); // undefined. 
  //Due to hoisting
  var c = 2;
}
It is not hoisted.
Example:
{
  console.log(b); // ReferenceError: 
  //b is not defined
  let b = 3;
}