原文: https://howtodoinjava.com/typescript/var-let-const/

在原始 JavaScript 中,变量是使用“var”关键字声明的。 现在,在 ES6 中,您还可以使用letconst关键字定义变量。 这三个关键字都具有用于变量声明和初始化的标准语法,但是它们的范围和用法不同。 让我们了解这三个关键字之间的区别。

var关键字

关键字var具有传统的变量定义语法。 (可选)您可以使用值初始化变量。 如果您没有在var语句中初始化变量,则会自动为其分配 JavaScript 值undefined

  1. var value ; //value is 'undefined'
  2. var data = 100; //initialized with number 100
  3. var blogName = 'howtodoinjava.com'; //initialized with string value

1)范围

  • var关键字声明的变量具有函数范围(即声明它们的函数内部的全局范围); 这意味着它们可以被共享同一作用域的任何函数访问。 ```java function fun() { var dataX = 10; //Globally available inside function fun()

    if(true) {

    1. var dataY = 20; //Globally available inside function fun()
    2. console.log(dataX); //Output 10
    3. console.log(dataY); //Output 20

    }

    console.log(dataX); //Output 10 console.log(dataY); //Output 20 }

fun();

console.log(dataX); //Not available outside function; dataX is undefined console.log(dataY); //Not available outside function; dataY is undefined

  1. -
  2. 可以在声明或初始化变量之前使用它们。 在这种情况下,它们的值为`undefined`,但不会出现任何运行时错误。
  3. ```java
  4. function fun()
  5. {
  6. console.log(dataX); //Output 'undefined'
  7. var dataX = 10;
  8. }
  9. fun();

2)var声明的提升

请注意,用var关键字声明的变量将被提升。 提升意味着,如果我们在函数末尾声明一个变量(已声明但未初始化),则运行时会将其提升到顶部,并且如果在声明之前使用该变量,则不会有任何错误。

阅读更多: JavaScript 提升

3)如果您不使用“var”关键字

在 JavaScript 中,如果不使用var关键字进行变量声明(隐式声明),则会在全局范围内创建变量。 例如:

  1. for(index=0; index< array.length; index++){ //index is in global scope
  2. //code
  3. }

for循环上方,将在全局范围内创建一个名为index的变量。 如果其他人碰巧也在使用全局index变量,那么您刚刚覆盖了他们的变量。

为避免赋予变量全局范围,必须在变量声明中使用var关键字。

let关键字

let关键字与var关键字非常相似 – 范围界定上有更多限制。

  1. 当“作用域必须限制在声明它的块中”时,使用“let”语句声明一个变量。 ```java function fun() { let dataX = 10;

    if(true) {

    1. let dataY = 20;
    2. console.log(dataX); //Output 10
    3. console.log(dataY); //Output 20

    }

    console.log(dataX); //Output 10 console.log(dataY); //dataY is ‘undefined’ }

fun();

  1. <br />参见上面突出显示的行。 如果您使用了“`var`”关键字,则由于`dataY`在函数中具有全局作用域,因此该名称已经可用。 由于`let`关键字,`dataY`在`if`块之外不可见。
  2. 2.
  3. 使用`let`声明的变量不能在声明之前使用,否则将导致错误。
  4. ```java
  5. function fun()
  6. {
  7. console.log(x); //Output 'undefined'
  8. console.log(y); //Error - "Uncaught ReferenceError: y is not defined"
  9. var x = 10;
  10. let y = 11;
  11. }
  12. fun();

const关键字

  1. const声明一个具有常量值的块范围变量。 它基本上是带有“var”关键字的变量声明,其中变量值是常量,不能更改。
  2. const遵循与let关键字相同的作用域原则。
  3. 如果您知道所声明的变量不能且不应被允许重新分配,则使用const对其进行声明,否则请使用let关键字。

语法和用法

  1. const PI = "3.14";
  2. PI = 12; //Uncaught TypeError: Assignment to constant variable.

将我的问题放在评论部分。

学习愉快!