Hoisting in Javascript

Hoisting in Javascript

Hoisting is a term used in JavaScript to describe the behavior of variable and function declarations being moved (or "hoisted") to the top of their respective scopes during the compilation phase, before the code is executed. This means that regardless of where a variable or function is declared within a scope, it is as if it was declared at the top of the scope.

For example, consider the following code:

console.log(x);
var x = 10;

Even though the variable `x` is declared and initialized on the second line, the code will not throw an error. This is because the variable declaration is hoisted to the top of its scope (in this case, the global scope), effectively making the code equivalent to:

var x;
console.log(x);
x = 10;

Similarly, function declarations are also hoisted to the top of their scope. For example:

foo(); // "hello"

function foo() {
  console.log("hello");
}

In this case, even though `foo()` is called before it is declared, the code will run without error, because the function declaration is hoisted to the top of its scope, effectively making the code equivalent to:

function foo() {
  console.log("hello");
}

foo(); // "hello"

However, it's important to note that hoisting only applies to variable and function declarations, not to variable assignments or function expressions. For example:

console.log(x); // undefined

var x = 10;

console.log(y); // ReferenceError: y is not defined

y = 20;

In the first case, even though the variable `x` is declared at the top of its scope, it is not initialized until the second line, so its value is `undefined` . In the second case, `y` is not declared or initialized at all, so a `ReferenceError` is thrown when the code tries to access it.