Horje
How Hoisting works in JavaScript ?

In JavaScript, hoisting is a mechanism where variable and function declarations are moved to the top of their containing scope during the compilation phase. This means that you can use a variable or call a function before it is declared in your code.

Example 1: Here, Even though the console.log(x) appears before the variable x is assigned a value, it doesn’t result in an error. This is because, during hoisting, the variable declaration is moved to the top, but the assignment remains in its original position.

Javascript

console.log(x); // Outputs: undefined
var x = 5;
console.log(x); // Outputs: 5

Output

undefined
5

Example 2: Here, the function sayHello is called before its declaration in the code. Hoisting moves the entire function declaration to the top, allowing the call to work without errors.

Javascript

sayHello(); // Outputs: "Hello, world!"
function sayHello() {
  console.log("Hello, world!");
}

Output

Hello, world!



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
How to Handle Errors in JavaScript ? How to Handle Errors in JavaScript ?
What is Function Currying in JavaScript ? What is Function Currying in JavaScript ?
What is the use of the Array.from() method in JavaScript ? What is the use of the Array.from() method in JavaScript ?
What are Classes in ES6 ? What are Classes in ES6 ?
How do we use the encodeURIComponent() function in JavaScript ? How do we use the encodeURIComponent() function in JavaScript ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14