Use of let, const, var in Javascript

  • 1. Variables
  • Two, let
  • Three, const
  • Four, var
  • Summarize

    1. Variables

    One of these three keywords can be used when defining variables in JS: let, const, var.

    Two, let

    General usage:

  • let a;

  • let name = 'Simon';

  • let is used to define block-level variables that are visible within the block it defines:

    // myLetVariable is not visible here

    for (let myLetVariable = 0; myLetVariable < 5; myLetVariable++) {   // myLetVariable is only visible here }

    // myLetVariable is not visible here

    3. const
    const is used to define variables that cannot be reassigned, that is, constants.
    const is also only visible within the block in which it is defined.

    const Pi = 3.14; // variable Pi is set
    Pi = 1; // An error will be reported here, because the constant cannot be reassigned
    1
    2
    4. var
    var is the most commonly used declaration variable keyword in JS before, it has no let and const-like constraints.
    A variable declared with var is visible within the function in which it is declared.
    General usage:

    var a;
    var name = 'Simon';
    1
    2
    Visible range:

    // myVarVariable is visible here

    for (var myVarVariable = 0; myVarVariable < 5; myVarVariable++) {   // myVarVariable is visible here }

    // myVarVariable can be seen here

    To summarize
    an important difference between JS and Java is that code blocks in JS have no scope, only functions have scope.
    If you use var to declare a variable in if, this variable will be visible in the entire function where if is located.
    Before ECMAScript 2015 only var was available.
    After ECMAScript 2015, let and const are available, which are convenient for defining block scope variables.
     

Guess you like

Origin blog.csdn.net/Ass12454548/article/details/128590962