Before We encounter problems and solve them let's recap what Javascript hoisting really is.
Hosting in javascript is a behavior where the variable and function declaration is moved to the top of the scope.
The scope can be local, or global.
x = 20 ;
console.log(x); // 20
var x ;
X will be hoisted to the top of the scope ( Global ) thus consoling the x will result in 20.
How does hoisting behave with let, const?
Let and const get HOISTED but for time being we cannot access them until they are initialized
This generally refers to a term called Temporal Dead Zone
console.log(b);
let b = 100;
// Cannot access 'b' before initialization"
Recap done let's encounter these 5 problems!
Q1: Predict the output.
(function random(){
x++;
console.log(x);
var x = 21;
})();
Output : NaN
// if we try to do hoisting here in the function scope
(function random(){
var x; // hoisted to the Top
x++; // here x is undefined
console.log(x) // NaN
x = 21;
})();
Q2: Guess the output?
doSomething();
function doSomething(){
x = 33;
console.log(x);
var x;
}
Output: 33
As var x gets hoisted and initialized with 33.
Q 3: Output of this Problem?
var b = 1;
console.log(c);
var c = 2;
a = 1;
console.log(a);
Output : undefined, 1
As c was undefined due to hoisting and a new variable created a = 1 so it result into 1
Q4: Predict the output.
makeStringReverse();
var reverse = "*/" ;
function makeStringReverse(){
console.log(reverse);
reverse = "/*" ;
}
console.log(reverse);
Output
undefined
“ */ “
Explanation
// actual execution flow
var reverse; // reverse is undefined atm
function makeStringReverse(){
console.log(reverse); // undefined
reverse = "/*" ; // initialized
}
makeStringReverse(); // called before reverse been initialized with "*/"
reverse = "*/" ;
console.log(reverse); // will console "*/" because it reverse was reassigned again.
Q5:
function callName() {
var name = "John";
}
callName();
console.log(name);
Output
Reference Error: name not defined
Explanation :
The simple reason for reference error is the scope in which the variable was hoisted.
It hoisted in the callName function scope but not in the global scope hence the error occurred.
That was it folks!
Hope this might helped you clearify hoisting in javasxript :)
Bbye!!
Top comments (0)