Using variables in Javascript - a very brief explanation
- Published on
Overview
Let's see how to use variables in Javascript.
[Figure 1 - Variable declaration keywords]
flowchart LR
let["let (mutable)"]
const["const (immutable)"]
subgraph ES6["ES6 (ECMAScript 2015)"]
let
const
end
var --> let
var --> const
- Since
ES6,varhas been improved toletandconst. var- a variable that can be declared as a function or a global scope, which is the way variables were declared beforeES6.let,const- variables that can be declared as block scoped, which was added inES6. In the case ofconst, the value cannot be changed after declaration and initialisation.
Hoisting
This is how all declarations (variables, functions, classes) are moved to the top of the pre-execution scope and behave as if they were declared there.
Variable hoisting behaviour:
var- is automatically initialised toundefinedwhen hosted (i.e. there is noTemporal Dead Zone).- The
letandconstare hoisted, but they are not automatically initialised, so there is no effect of hoisting due to theTemporal Dead Zone. (i.e. don't bother)
In the case of let and const, the declaration is moved to the top by hoisting, but there is a Temporal Dead Zone where the variable cannot be referenced until the statement where the let and const were originally declared (where it is initialised), and a ReferenceError is thrown if the variable is referenced.
console.log(a); var a; a = 42; // undefined
console.log(b); let b; b = 42; //ReferenceError: b is not defined
console.log(c); const c = 42; //ReferenceError: c is not defined
let, const are scoped and applied on a block basis
let a = 10;
{ // new block scope
//console.log(a); // ReferenceError: Cannot access 'a' before initialization
let a = 20;
console.log(a); // 20
}
console.log(a); // 10
Conclusion
- Use
const, and only useletif you need to change the value in the middle. - When reading code that uses
var, be aware of variable hosting and variable scoping