DEV Community

Cover image for Solve 5 problems Based on Hoisting
Vipin Chandra
Vipin Chandra

Posted on

Solve 5 problems Based on Hoisting

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 ;
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

Recap done let's encounter these 5 problems!

Q1: Predict the output.

(function random(){
    x++;
    console.log(x);
    var x = 21;
  })();
Enter fullscreen mode Exit fullscreen mode

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; 
})();
Enter fullscreen mode Exit fullscreen mode

Q2: Guess the output?

doSomething();
function doSomething(){
  x = 33;
  console.log(x);
  var x;
}
Enter fullscreen mode Exit fullscreen mode

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);

Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

Q5:

function callName() {   
var name = "John";
} 
callName();
console.log(name);
Enter fullscreen mode Exit fullscreen mode

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)