Understanding Hoisting in JavaScript
In JavaScript, hoisting is a mechanism that shifts variable and function declarations to the beginning of their scope before the code is executed. This means that you can use variables and functions before they are declared in your code.
But remember, only the declarations move to the top, not the actual values assigned. Now, let’s see some examples of hoisting with variables and functions.
Variable Hoisting
In JavaScript, the sequence of variable declarations can be summarized based on the type of declaration (var, let, const) and the scope in which they are declared. Here’s a general overview:
console.log(a); // ReferenceError: Cannot access 'a' before initialization
let a; // Declaration
a = 100; // Assignment
console.log(a); // Usage
Output
ReferenceError: Cannot access ‘a’ before initialization The variable a is hoisted to the top of the scope, so the first console.log doesn’t result in an error.
However, it logs undefined because the assignment (var a = 5;) is not hoisted, and at the time of the first console.
log, a has been declared but not yet assigned. To prevent this issue, we can ensure to both declare and assign the variable simultaneously before using it.
Function Hoisting
Function declarations are fully hoisted, including both the declaration and the function definition.
sayHi(); // "Hi!"
function sayHi() {
console.log("Hi!");
}
Output
Hi!
The function sayHi is called before its actual declaration in the code. However, due to hoisting in JavaScript, the function declaration is moved to the top of its containing scope during the compilation phase.
JavaScript functions can be loosely classified into several categories based on their characteristics and use cases. Here are some common classifications:
The details are given below:
1. Function Declarations
Defined using the function keyword.
Hoisted to the top of their containing scope during compilation.
Can be called before the actual declaration in the code.
Example:
function sayHi() {
console.log("Hi!");
}
2. Function expressions
Created by assigning a function to a variable.
Not hoisted in the same way as function declarations.
The variable can be used only after the assignment.
Example:
var sayHi() = function() {
console.log("Hi!");
}
Conclusion
Hoisting is a mechanism where JavaScript moves variable and function declarations to the top of their scope during the compile phase. This allows variables and functions to be used before their actual declarations in the code. Remember, variable declarations are hoisted without their initializations, and function declarations are fully hoisted. Understanding hoisting helps in writing predictable and maintainable code.