JavaScript From Beginner To Advanced

0% completed

Previous
Next
JavaScript - Hoisting

Hoisting is a behavior in JavaScript where variable and function declarations are moved to the top of their containing scope before code execution. This mechanism allows variables and functions to be accessed before their actual point of declaration in the script. Understanding hoisting is crucial for debugging and writing reliable JavaScript code.

Variable Hoisting

Variable hoisting refers to the way JavaScript treats variable declarations during the compilation phase. Variables declared with var are hoisted to the top of their functional or global scope, though their initialization is not.

Example 1: Hoisting with var

Javascript
Javascript

. . . .

Explanation:

  • First console.log(myVar);:
    • Attempts to log myVar before it is initialized. Due to hoisting, the declaration var myVar is moved to the top, but it is initialized at its original location. Thus, it logs undefined.
  • Initialization var myVar = 5;:
    • myVar is assigned the value 5 here.
  • Second console.log(myVar);:
    • Now that myVar is initialized, it logs 5.

Hoisting with let and const

Unlike var, variables declared with let and const are not hoisted at the top. Accessing them before the declaration results in a ReferenceError.

Example 2: Hoisting with let

Javascript
Javascript

. . . .

Explanation:

  • console.log(myLet);:
    • This line will throw a ReferenceError because myLet is in the temporal dead zone at this point. It's hoisted but not initialized.
  • let myLet = 10;:
    • myLet is initialized here, making it safely accessible after this point.

Function Hoisting

Function hoisting allows function declarations to be lifted to the top of their containing scope. This means that functions can be called before they are declared in the source code.

Example 3: Function Hoisting

Javascript
Javascript

. . . .

Explanation:

  • console.log(sum(3, 4));:
    • Calls the sum function before it appears in the code. Function hoisting allows this by moving the function declaration to the top of the scope.
  • function sum(x, y) {...}:
    • The function is defined here, but due to hoisting, it is as if it were placed at the top of the scope. It correctly computes and returns the sum of 3 and 4, which is 7.

Hoisting is a fundamental concept in JavaScript that can lead to subtle bugs if not properly understood. By clearly comprehending how variable and function hoisting works, developers can write more predictable and error-free code. Recognizing the differences in hoisting behavior between var, let, const, and function declarations is critical for effective JavaScript programming.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next