Embarrassment about getting up

consider these slightly two different versions of lifting ...

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

      

This will print "fingal" followed by "fingal"

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

      

This will print "undefined" and "fingal"

Why?

+3


source to share


5 answers


As soon as you declare a variable using a keyword var

in a javascript function, and no matter where you place that declaration - at the top of the function or in the buttom, it will be considered a local variable. Therefore, you get undefined

when you try to get the value of such a variable before the declaration var

.



+6


source


In the second option, you hide mylocation

(which I hope was declared in the outer scope.) With a new variable through the declaration var

.



"In JavaScript, a variable can be declared after use." meaning: JavaScript pulls declarations var

to the beginning of the scope ( No matter where it was declared! ), so in your second function it is var mylocation

implicitly defined but not assigned before the first alert, so it outputs undefined

at that point.

+5


source


The output of the first snippet must be "dublin" and "fingal" provided mylocation is defined, otherwise it is a link error.

More details:

http://bustingseams.blogspot.in/2009/08/another-javascript-pitfall-hoisting.html

0


source


In JavaScript - variable declarations are hoisted, but initialization is not. This means that when you write var

anywhere inside a function, it will be treated as declared at the top. Therefore, it will not accept the same name variable from the global space.

@Ashish is right, the first snippet should output "dublin" and "fingal".

0


source


Take for example:

x = 5;
var x;

console.log( x );

      

Technically, you might look x = 5;

like the wrong operator in this context, given the fact that it comes before the declaration, but JS Engine doesn't work that way. He sees x = 5

and var x

as two separate operator, first - connected with the task of the compiler, and the second related to the execution of the task.

what this means in simple terms is that all declarations in the scope, no matter where they appear, are processed first before the code itself is executed. you can execute a variable before declaring it.

0


source







All Articles