Hoisting is a behaviour in JavaScript where variable and function declarations are moved to the top of their respective scopes during the compilation phase, allowing them to be accessed before they are actually defined in the code. It is important to note that only the declarations themselves are hoisted, not the initializations or assignments.
The concept of hoisting can sometimes lead to confusion and unexpected results if not properly understood. Therefore, it is crucial to have a comprehensive understanding of how hoisting works in JavaScript. In this explanation, we will delve into hoisting in detail, providing examples to illustrate its behaviour.
Variable Hoisting:
Let’s start with variable hoisting. In JavaScript, variables declared with the var
keyword are hoisted to the top of their scope during the compilation phase. However, only the declaration is hoisted, not the assignment or initialization. This means that while the variable name is accessible throughout the scope, its value will be undefined
until the assignment is encountered.
console.log(x); // Output: undefined
var x = 5;
In the example above, the variable x
is declared and assigned a value of 5. However, when we try to log its value before the declaration, we get undefined
instead of a ReferenceError…