Initialization vs assignment

后端 未结 1 1378
走了就别回头了
走了就别回头了 2021-01-24 10:17

The terms \"initialization\" and \"assignment\" seem to be used interchangeably. I did some searching and it seems that there might technically be a difference. My understanding

相关标签:
1条回答
  • 2021-01-24 10:35

    TLDR:

    { // declaration (hoisted)
      // Temporal deadzone
      let foo; // declaration and initialization to undefined
      foo = 1; // assignment
    }
    

    A bit longer:

    Declaration

    Declaring a variable means that we reserve the identifier at the current scope. In javascript declarations are hoisted, that means that it gets declared when the scope the variable is in gets visible (the block it is in gets executed). However you cannot access that variable now as it is in

    The temporal deadzone

    This is a specific part of the code that is between the beginning of the scope and the initialization. Trying to access the variable here results in an error.

    Initialization

    The initialization takes place in the line were you declared the variable. It will assign a value to the variable and will make it available for access. This for example:

    let foo;
    

    will initialize foo to undefined,

    let foo = 2;
    

    will initialize foo to 2.

    Assignment

    ...just means that you change the value of a variable. All assignments in javascript use =. The initialization is basically just the first assinment.

    The explanation above does not apply to variables declared with var, so just don't use var to avoid confusion :)

    0 讨论(0)
提交回复
热议问题