Hoisting in JavaScript

JavaScript Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, prior to execution of the code.

Conceptually variable hoisting is often presented as the interpreter “splitting variable declaration and initialization, and moving (just) the declarations to the top of the code”. As explained in the execution context, this occurs during the Creation phase. In this phase, JavaScript allocates memory for every variable and initializes them with the value undefined before executing the code.

In the below example you are getting the value if num as undefined in the first line itself, that means it has been intialized in the Global scope before the line of decalaration in the code.

console.log(num); // Returns 'undefined' from hoisted var declaration (not 6)
var num; // Declaration
num = 6; // Initialization
console.log(num); // Returns 6 after the line with initialization is executed.

The same thing happens if you declare and initialize the variable in the same line.

console.log(num); // Returns 'undefined' from hoisted var declaration (not 6)
var num = 6; // Initialization and declaration.
console.log(num); // Returns 6 after the line with initialization is executed.

To avoid bugs, always declare all variables at the beginning of every scope. Since this is how JavaScript interprets the code, it is always a good rule.

JavaScript in strict mode does not allow variables to be used if they are not declared.

References

w3schools


Read More