JS declarations: const, let, and var
May 23, 2020 by Jane

var

 

Global variables defined with the var keyword belong to the window object. 

E.g. var myname = "Jane"; // we can access myname using window object i.e. window.myname will return "Jane"

E.g. let myname = "Sonia"; // we can NOT access myname using the window object 

 

let

 

let is a ES5 keyword that declares a local variable inside a scope (defined by {}). 

Global variables defined with the let keyword do NOT belong to the window object unlike variables declared with var

let variables can only be redeclared in a different scope than an existing let variable.

Hoisting doesn't happen to let variables, so the variables must be declared before they can be used

 

const

const is an ES5 keyword that declares a local variable inside a scope (defined by {}). 

const is like let, except the variable cannot be reassigned any other values. Similar to constexpr in C++, the const variables must be initialized at declaration.

Although const variables cannot be reassigned, they can be modified. Objects' properties and array's elements can be modified and have push(), pop() operations performed on them.

Similar rules apply to const variables as let variables in terms of redeclaration and hoisting.