Home / javascript / What is hoisting in javascript with example?

What is hoisting in javascript with example?

Hoisting in JavaScript is a behavior where variable and function declarations are moved to the top of their containing scope during the compilation phase, regardless of where they are declared in the code. This means that you can access variables and functions before they are declared in your code.

However, it’s important to understand that only the declarations are hoisted, not the initializations or assignments. Here are a few key points about hoisting:

1. **Variable Declarations:** When you declare a variable using `var`, `let`, or `const`, the declaration is hoisted to the top of its containing function or global scope. If you try to access the variable before its declaration, it will exist but have the value `undefined`.

   console.log(x); // Output: undefined
   var x = 10;

2. **Function Declarations:** Function declarations are also hoisted to the top of their containing scope. This means you can call a function before it appears in the code.
   greet(); // Output: "Hello, World!"

   function greet() {
       console.log("Hello, World!");
   }

3. **Function Expressions:** However, function expressions (where a function is assigned to a variable) are not hoisted in the same way. Only the variable declaration is hoisted, not the function assignment.

   greet(); // This will throw an error

   var greet = function() {
       console.log("Hello, World!");
   };

Here are a few more examples to illustrate hoisting in JavaScript:

console.log(x); // Output: undefined
var x = 10;
console.log(x); // Output: 10

In this example, the declaration of the variable x is hoisted to the top of the scope, but the initialization (var x = 10;) remains in place. Therefore, when console.log(x) is executed before the initialization, x exists but has the value undefined.

var x = 10;

function example() {
    console.log(x); // Output: undefined
    var x = 20;
    console.log(x); // Output: 20
}

example();
console.log(x); // Output: 10

In this example, within the example function, the declaration var x = 20; is hoisted to the top of the function’s scope, but not its initialization. Therefore, the first console.log(x) prints undefined. The x within the function is a different variable than the global x.

About Sushil Kumar

Check Also

What are the differences between var, let and const in JavaScript?

var, let, and const are all used for variable declaration in JavaScript, but they have …

Leave a Reply

Your email address will not be published. Required fields are marked *