Initialization vs assignment

拜拜、爱过 提交于 2019-12-02 12:09:45

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/50895174/initialization-vs-assignment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!