简体   繁体   中英

Undefined variable within a function

Look at the following snippet:

var fruit = "Orange";
echoThis();

function echoThis() {    
    alert(fruit);
    var fruit = "Apple";
}

When I run this snippet, the alert of fruit is undefined . Why?

First I thought it has something to do with hoisting, that within a funciton, the JS engine "lifts" all var declarations to the top or something, but then I would expect the alert to display Apple , not undefined .

There's probably some elementary JS behaviour I'm unaware of. Anyone care to explain?

JS fiddle: https://jsfiddle.net/z37230c9/

It's because of hoisting . Variables declared in a function are available for the entire scope, but they are assigned a value where you put it.

This:

function echoThis() {    
    alert(fruit);
    var fruit = "Apple";
}

becomes this:

function echoThis() {    
   var fruit;
   alert(fruit);
   fruit = "Apple";
}

This is why you code is evaluated successfully, but fruit's value is undefined.

also:

var fruit = "Orange"; //this fruit variable
echoThis();

function echoThis() {    
    alert(fruit);
    var fruit = "Apple"; // is overridden by this, 
     //because it's re-declared in a local scope. 
}

if you really want to change this then remove the var in the function.

   function echoThis() {    
        alert(fruit);
        fruit = "Apple";  //this now accesses the global fruit.
    }

The variable is hoisted to the top of the function when it is compiled.

function echoThis() {    
    alert(fruit);
    var fruit = "Apple";
}

Translates to this

function echoThis() {    
    var fruit;
    alert(fruit);
    fruit = "Apple";
}

So when the alert is called it is technically undefined at this point. To stop seeing that move your variable declaration before the alert statement.

that's because js has lexical scope and hoisting.

so echoThis looks for fruit within itself before looking outside and since you have var fruit = "Apple"; , fruit is hoisted in echoThis .

Besides the above responses, if you want to get the orange AND the apple after.. you could try to pass the variable simply as a parameter and work in the function

 var fruit = "Orange"; echoThis(fruit); function echoThis(fruit) { alert(fruit); // You will get the orange var fruit = "Apple"; alert(fruit); // You will get the apple } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM