Hoisting
- Hoisting is the default behavior of moving all the declarations at the top of the scope before code execution.
- It gives us an advantage that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local.
- It allows us to call functions before even writing them in our code.
1
2
3
4
5
| catName("Chloe");
function catName(name) {
console.log("My cat's name is " + name);
}
|
- Even though we call the function in our code first, before the function is written, the code still works. This is because of how context execution works in JavaScript.
- Hoisting works well with other data types and variables. The variables can be initialized and used before they are declared.
var, let, const
- var : A
function-scoped
or globally-scoped variable
, optionally initializing it to a value. - let : A
block-scoped
local variable
, optionally initializing it to a value. - const : A
block-scoped
local variable
, can’t be changed through reassignment, and it can’t be redeclared.
1
2
3
4
5
6
7
8
9
10
11
12
13
| var a = 1;
var b = 2;
if (a === 1) {
var a = 11; // the scope is global
let b = 22; // the scope is inside the if-block
console.log(a); // 11
console.log(b); // 22
}
console.log(a); // 11
console.log(b); // 2
|
1
2
3
4
5
6
7
8
9
10
11
12
| // define MY_FAV as a constant and give it the value 7
const MY_FAV = 7;
// this will throw an error - Uncaught TypeError: Assignment to constant variable.
MY_FAV = 20;
// MY_FAV is 7
console.log('my favorite number is: ' + MY_FAV);
// trying to redeclare a constant throws an error
// Uncaught SyntaxError: Identifier 'MY_FAV' has already been declared
const MY_FAV = 20;
|
Variable lifecycle
1
2
3
| var a; // Declaration
a = 100; // Assignment
console.log(a); // Usage
|
Declaration –> Initialisation/Assignment –> Usage
TDZ(Temporal Dead Zone)
let/const
are hoisted (like var, class and function), but there is a period(TDZ) between entering scope and being declared where they cannot be accessed.
1
2
| console.log(a); // undefined
var a = 10;
|
Declaration –> Initialisation/Assignment –> Usage
1
2
| console.log(a); // ReferenceError: Cannot access 'a' before initialization
let a = 10;
|
Declaration –> TDZ(Temporal Dead Zone) -> Initialisation/Assignment –> Usage
Reference