Initialization vs assignment

无人久伴 提交于 2019-12-02 04:23:56

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

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