Hoisting in JavaScript
https://scotch.io/tutorials/understanding-hoisting-in-javascript
What is Hoisting?
JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.
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.
undefined vs ReferenceError
undefined
undefined
In JavaScript, an undeclared variables is assigned the value
undefined
at execution and is also of type of undefined.
ReferenceError
ReferenceError
In JavaScript, a ReferenceError is thrown when trying to access a previously undeclared variable.
The behavior of JavaScript when handling variables becomes nuanced because of hoisting!
Hoisting variables
all
undeclared variables
are global variables
ex)
var
var
function scoped
ex)
JavaScript has hoisted the variable declaration
let
let
block scope
ex1)
ex2)
We should declare then assign our variables to a value before using them!
const
const
Introduced in ES6 to allow immutable variables
ex1)
ex2)
ex3)
the variable is hoisted to the top of the block
must be both declared and initialized before use.
Hoisting functions
JavaScript functions
Function declarations
Function expressions
Function declarations
Hoisted completely to the top
ex)
Function expressions
Not hoisted
ex)
Order of precedence
Variable
assignment takes precedence overfunction
declarationFunction
declarations take precedence over variable declarations
Function declarations are hoisted over variable declarations but not over variable assignments!
Hoisting classes
JavaScript Classes
Class declartions
Class expressions
Class declarations
Hoisted like function declarations
ex)
you have to declare a class before you can use it
Class expressions
Not hoisted like function expressions
ex)
Last updated