Hello everyone! π Let's talk about hoisting in JS.
What is Hoisting in JavaScript?
The term hoist means to "raise (something)" and in JS it is used to describe the behaviour of JS interpreter whereby the use of classes, functions and variables before their declaration does not cause the error: Uncaught ReferenceError: X is not defined
. This is because hoisting appears to have moved the declaration up to the top. (The variables and functions are actually saved in memory during the creation phase of the Execution Context, you can read more about it here.)
Below, I will talk about the difference between variable hoisting and function hoisting.
Variable Hoisting
When you declare a variable, you can use var
, let
and const
. Both let
and const
get hoisted but do not get initialized with a default value, this means that you can still get ReferenceError
if you use the variables before its declaration. However, for var
, when it gets hoisted it also gets initialized with a default value of undefined
so you will not get an error.
Example:
console.log(varThing); // undefined
var varThing = "testingVar";
console.log(letThing);
let letThing = "testingLet"; // Uncaught ReferenceError: Cannot access 'letThing' before initialization
Function Hoisting
When a function gets hoisted this means that you can call/use the function safely without error, this only applies to function created with function
keyword and not function expressions.
Example:
console.log(getRandomNumber(2, 5)); // 2
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
console.log(getRandom()); // Uncaught TypeError: getRandom is not a function
var getRandom = function () {
return Math.floor(Math.random() * 10)
}
In the example, you can see that the getRandomNumber
function can be called before its declaration, this is due to hoisting. However, with getRandom
, it has been hoisted as a variable, specifically with value undefined
and so you get a TypeError
when you try to use it as a function.
Summary
Hoisting is the term used to describe the process in which declarations of classes, functions and variables get saved in memory during the Execution Context. This allows for the program to read (use) these values before declaring them. It can cause some problems so it is good to know what kind of error it can cause but also why certain things work even before you declare them.
It is always best to declare your classes, expression functions and variables before using them to avoid initialization errors.
Thank you for reading, leave a comment if you found it helpful or have any feedback. π