What is Hosting in javascript with example

Hoisting in JavaScript is a behavior where variable and function declarations are moved to the top of their scope before code execution. This allows you to use variables and functions before declaring them in the code. Only the declaration is hoisted, not the initialization.

For example:

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

foo(); // Output: "Hello World"
function foo() {
    console.log("Hello World");
}

Here, var a is hoisted to the top but its value 10 is not, so it prints undefined. The function foo() is fully hoisted, so calling it before its declaration works fine.

Note: Variables declared with let and const are hoisted too but accessing them before declaration causes a ReferenceError.

Hoisting is useful to understand scope, execution context, and function behavior in JavaScript.

 

Lire la suite