// why does javascript have hoisting?
As Stoyan Stefanov explains in "JavaScript Patterns" book, the hoisting is
result of JavaScript interpreter implementation.
The JS code interpretation is performed in two passes.
a) During the first pass, the interpreter processes
variable[NOT the initialitations] and function declarations.
b)The second pass is the actual code execution step. The interpreter processes
function expressions and undeclared variables.
Thus, we can use the "hoisting" concept to describe such behavior.
var defaultname = "John";
var name = "rayn";
function doit() {
if(!name){
var name = defaultname;
}
return name;
}
var ourname = doit();
console.log(ourname); //John
// because name inside function will have more priority over outside name variable.
// And, this inside name variable will be declared in memory as undefined due to hoisting.
var a = 10;
{
var a = -10;
}
let b = a;
{
let b = -20;
}
console.log(b)
// program to display value
a = 5;
console.log(a);
var a; // 5