Hoisiting:
Hoisiting is basically it moves all declaraions
What is a 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.
... Variable and class declarations are also hoisted, so they too can be referenced before they are declared.
Hoisting allows functions to be safely used in code before they are declared.
Variable and class declarations are also hoisted, so they too can be referenced before they are declared. Note that doing so can lead to unexpected errors, and is not generally recommended.
Why hoisting happens in JavaScript?
JavaScript hoisting occurs during the creation phase of the execution context that moves the variable and function declarations to the top of the script. The JavaScript engine hoists the variables
declared using the let keyword, but it doesn't initialize them as the variables declared with the var keyword.
Dis-advantages of hoisting
Disadvantages are thaat memory is wasted since global scope variables are'nt cleared until browser is
closed and also anyone can change (read/write) it since its gloabel so we may not get expected result .
it is not encourage to maintain global variables
Functional scope variable are advantages since they are cleared after the completion of function execution
ex : functional Hoisting
catName("Tiger");
function catName(name) {
console.log("My cat's name is " + name);
}
The result of the code above is: "My cat's name is Tiger"
Ex 2 : Var Hoisting
console.log(num); // Returns 'undefined' from hoisted var declaration (not 6)
var num; // Declaration
num = 6; // Initialization
console.log(num);