Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused about hoisting

consider these slightly two different versions of hoisting...

mylocation = "dublin" 
function outputPosition() {
    alert(mylocation);
    mylocation = "fingal" ;
    alert(mylocation);
}
outputPosition();

This will output "fingal" and then "fingal"

mylocation = "dublin" 
function outputPosition() {
    alert(mylocation);
    var mylocation = "fingal" ;
    alert(mylocation);
}
outputPosition();

This will output "undefined" and "fingal"

Why?

like image 852
dublintech Avatar asked Nov 02 '25 10:11

dublintech


1 Answers

Once you declare variable using var keyword within a javascript function and no matter where you put this declaration - at the top of the function or at the buttom, it will be considered as local variable. So that is why you get undefined when you try to get value of such variable before var declaration.

like image 170
aliona Avatar answered Nov 04 '25 01:11

aliona



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!