Hoisting in JavaScript 🔥(variables & functions)

5 months ago
5

In this illustration:

We declare a variable x using var, and then try to log its value before the actual assignment. Due to hoisting, the variable declaration is moved to the top of its scope, and console.log(x) does not throw an error but outputs undefined.

The hoistingExample function demonstrates hoisting within a function scope. The variable y is declared within an if block but is still accessible outside the block due to hoisting.

Function declarations are hoisted as well. The sayHello function is called before its declaration, and it works without any errors.

However, function expressions (like var sayHi = function () {...}) are not hoisted in the same way. If you try to call sayHi before its declaration, it will result in a TypeError.

Understanding hoisting helps in writing more predictable and error-free JavaScript code. It's essential to be aware of how variable and function declarations are processed during the compilation phase.

Loading comments...