This lesson is only accessible in the paid version of the course.
Get access to all lessons 💫 price: 34.99$
Do you speak JavaScript?
We will explore the mechanics of hoisting and how it affects the behavior of your code, as well as best practices for working with hoisted variables and functions.
Hoisting in JavaScript refers to the behavior of variable and function declarations being moved to the top of their scope during the compilation phase. This means that, regardless of where a variable or function is declared in the code, it is accessible within its scope as soon as the interpreter encounters the variable or function declaration.
In terms of variables, variables declared with the var keyword are hoisted to the top of their scope and are initialized with a value of undefined. This means that you can access a variable before it is declared in the code, but its value will be undefined. For example:
console.log(hoistedVar); // undefined
var hoistedVar = "I am a hoisted variable";
Here, the variable hoistedVar
is hoisted to the top of its scope and is initialized with a value of undefined
, so when we try to access it before the actual declaration, we get undefined
.
On the other hand, variables declared with the let
and const
keyword are not hoisted and will result in a ReferenceError
if we try to access them before they are declared.
In terms of functions, function declarations are also hoisted to the top of their scope. This means that you can call a function before it is declared in the code. For example:
hoistedFunction(); // "I am a hoisted function"
function hoistedFunction() {
console.log("I am a hoisted function");
}
Here, the function hoistedFunction
is hoisted to the top of its scope, so we can call it before its actual declaration and it will work as expected. Not every function declaration is hoisted though. Only the ones that use the function
keyword.
It's important to note that hoisting applies only to declarations and not to assignment. Hoisting is a behavior that happens during the compilation phase, and it's not something you can control. Understanding how hoisting works can help you to write better and more maintainable code.
Practice is the fastest way to learn knowledge permanently. I have prepared a small task for you related to the lesson.
Materials related to the lesson:
→ Files associated with the lesson