Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hoisting variables in JavaScript

Tags:

javascript

I understand Hoisting of variables is done in Java Script. I am unable to get why it outputs as undefined

 do_something()
    {
    var foo = 2;    
    console.log(foo);   
    } do_something()  // it prints 2

 do_something()
     {        
     console.log(foo);  var foo = 2;  
     } do_something()  // it prints undefined

As javascript do hoisting the second function also should print 2 as per my understand.buy why doesn't it

like image 341
Vinny Avatar asked Mar 12 '23 19:03

Vinny


2 Answers

This is how the interpreter sees your code,

do_something() {
 var foo;
 console.log(foo); // undefined
 foo = 2;
}

do_something();

So it is printing undefined. This is a basic of variable hoisting. Your declarations will be moved to the top, and your assignation will remain in the same place. And the case is different when you use let over var.

like image 99
Rajaprabhu Aravindasamy Avatar answered Mar 25 '23 03:03

Rajaprabhu Aravindasamy


Javascript only hoists declarations, not initializations.

var x = y, y = 'A';
console.log(x + y); // undefinedA

Here, x and y are declared before any code is executed, the assignments occur later. At the time "x = y" is evaluated, y exists so no ReferenceError is thrown and its value is 'undefined'. So, x is assigned the undefined value. Then, y is assigned a value of 'A'. Consequently, after the first line, x === undefined && y === 'A', hence the result.

Variable Declaration

like image 41
jacksparrow92 Avatar answered Mar 25 '23 05:03

jacksparrow92