Hoisting in JavaScript

Hoisting in JavaScript

In JavaScript, hoisting is a behavior in which variable and function declarations are moved to the top of their containing scope (like the top of a function or the top of a script) during the compile phase, before the code is executed. This means you can use a function or variable before you've actually declared it in your code.

Variable Hoisting:

  • Only the declarations of var variables are hoisted, not the initializations.
  • let and const variables are also hoisted, but they are not initialized. They remain in a "temporal dead zone" from the start of the block until the declaration is encountered.

Here's a super simple example:

console.log(x); // Output: undefined (because x is hoisted but not initialized)
var x = 5;

console.log(y); // ReferenceError: y is not defined (y is in the temporal dead zone)
let y = 10        

Even though x is used before it's declared, JavaScript "hoists" the declaration to the top of the code, so it doesn't cause an error.

var variables are hoisted and initialized with undefined, allowing them to be accessed even before declaration. On the other hand, let variables are hoisted but not initialized, resulting in a ReferenceError if accessed before the actual declaration.

Function Hoisting:

  • Function declarations are fully hoisted, meaning you can call the function before its declaration in the code.
  • Function expressions (including those defined using var, let, or const) are not hoisted in the same way.

Example 1 :

console.log(foo()); // Output: "Hello, World!" (function is hoisted)
function foo() {
return "Hello, World!";
}        

  • Hoisting Behavior: Function declarations are hoisted to the top of their scope. This means both the declaration and the function definition are moved to the top during the compile phase.
  • Result: This allows you to call the function foo before its actual declaration in the code. So, console.log(foo()); works perfectly and prints "Hello, World!".

It's as if the code was written like this:

function foo() {
    return "Hello, World!";
}
console.log(foo()); // "Hello, World!"        

Example 2 :

console.log(bar()); // TypeError: bar is not a function (bar is not hoisted)
var bar = function() {
    return "Hello, again!";
};        

  • Hoisting Behavior: Variable declarations (var) are hoisted, but their assignments are not. Function expressions are not hoisted in the same way function declarations are.
  • Result: When the code executes console.log(bar());, bar is hoisted and exists, but it is undefined at that point, not a function. This results in a TypeError because you are trying to call something that is not yet a function.

It's as if the code was written like this:

var bar; // Variable declaration is hoisted
console.log(bar()); // TypeError: bar is not a function (bar is still undefined)
bar = function() {
    return "Hello, again!";
};        

In summary:

  • Function Declarations (foo) are hoisted completely, so you can call them before their declaration.
  • Function Expressions (bar), when defined with var, have their variable declarations hoisted, but not their assignments. So, the variable exists but is not assigned the function until the line where the function expression is defined.

So, hoisting is like JavaScript preparing a cheat sheet by moving the declarations to the top before running your code! Understanding hoisting is important for writing clear and predictable JavaScript code. It helps you know when and where variables and functions can be safely used, minimizing unexpected behaviors.

To view or add a comment, sign in

More articles by Vaishnavi Pampatwar

  • Angular Change Detection

    Angular change detection is an essential part of the Angular framework, designed to keep your application's data in…

    3 Comments
  • Autoboxing In JS

    Autoboxing in JavaScript refers to the automatic conversion of primitive data types to their corresponding object…

  • Async and defer in JavaScript

    In JavaScript, and are attributes you can add to tags to control how scripts are loaded and executed. They are…

  • Throttling in JS

    What is Throttling? Throttling is a programming technique used to control the rate at which a function is executed…

  • Storage in JavaScript

    In JavaScript, "storage" refers to the various ways you can store data on the client-side, within the user's browser…

  • Debouncing in JavaScript

    Debouncing in JavaScript is a technique used to ensure that a function isn't called too frequently. It limits the rate…

  • Enumerable In JS

    In JavaScript, enumerable properties are those that can be looped over using loops or accessed via methods like…

    2 Comments
  • Clousers in JS

    Closures are a powerful and often misunderstood feature of JavaScript where a function has access to its own scope, the…

  • Shallow Copy And Deep Copy

    Shallow copy and deep copy are two different ways of copying objects in JavaScript. They determine how the objects are…

  • Async/await

    Async/await is a modern way to handle asynchronous operations in JavaScript, making your code look and behave more like…

Others also viewed

Explore content categories