Hoisting in JavaScript

Hoisting in JavaScript

In JavaScript hoisting refers to the process by which the variable and function are moved to the top of their respective scope. This behavior is applied to both global and local scopes.

Here are some examples to illustrate hoisting

Example 1: Variable hoisting

console.log(num);
var num = 25;

// output: undefined

While num appears declared after its use, it's hosted to the top of the scope, allowing its references (but not its initial value) before the actual declaration line

It's important to note that only the declarations are hoisted, not the initializations. In the example above, the num declaration is hoisted, but its assignment is not hoisted. As a result, the console.log outputs undefined.

Example 2: Function hoisting

sayHello();
function saHellow(){
    console.log("Hello readers");
}

// output: Hello readers

In the above code, sayHello is defined after it call and JavaScript acts as if it were declared at the beginning of the scope, enabling its smooth execution.

However, if you try to call an anonymous function expression before its declaration it will give an error

greet(); // Error: greet is not a function

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

In the example above, the variable greet is hoisted, but at the time of the function call, the assignment (var greet = function() { ... }) has not happened yet, leading to a TypeError.

Example 3: Hoisting within Local Scopes

function result() {
 num = 100 //     Hoisting within the function
 console.log(num) 
 var num;
}
result();

Here num is hoisted to the top of the result function which allows its use before its explicit declaration

Hoisting in Strict Mode:

In strict mode, attempting to assign a value to an undeclared variable results in a ReferenceError. This is in contrast to the non-strict mode, where the variable would be implicitly declared as a global variable.

Let's see example in case of strict mode

"use strict";

console.log(myVariable); // Throws a ReferenceError
myVariable = "Hello, World!"; // This line is not executed due to the error
console.log(myVariable); // This line is not executed due to the error

In strict mode, attempting to access an undeclared variable results in a ReferenceError immediately. This helps catch potential issues earlier in the development process.

if you like this article let's connect on LinkedInlinkedin.com/in/shivamgupta6418

Did you find this article valuable?

Support Shivam's Blog❤️❤️ by becoming a sponsor. Any amount is appreciated!