Search code examples
javascriptcomputer-science

Initialization vs assignment


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 is that, in the context of variables, a variable is initialized when the JavaScript engine makes it available for use, and assignment (whether done explicitly [as in let foo = 1;] or by the JavaScript engine, as in the following example) is one way to achieve this.

let foo;
console.log(foo); // undefined (initialization and assignment?)

Is my understanding correct? Also (if so), what actually occurs during initialization to make the variable available?


Solution

  • 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 :)