Published on August 1, 2021
Var, Let and Const
const. Previously, the keyword
var was the only way to do so.
const were introduced because there were issues with
var which made it error-prone and hard to debug.
|Scope||Global or Function||Block scope ||Block scope |
|Must be initialized when declared||No||No||Yes|
|Can use before initialization||Yes||No||No|
|Can be redeclared||Yes||No||No|
|Can be updated||Yes||Yes||No|
|Hoisted to start of scope||Yes||Yes||Yes|
var because it is either global or function scope, and a declaration and assignment of a
var can easily be redeclared or updated unknowingly in another function. Furthermore, a
var is initialized with
undefined and can be used even before being assigned a value.
On the other hand,
const are block scope, and cannot be redeclared. Additionally,
const cannot be updated. Both
const also cannot be used before initialization, and will throw
Reference error rather than return