Variable Scope - Demo 3

This page demonstrates code with 3 different contexts. It produces an error because a nested function that is not available in the global context is executed from the global context.

Here is the code:

var sport = "baseball";   
var player = null;   
  
function getPlayer() {   
    if (sport === "baseball") {   
        player = "Evan Longoria";   
    } else {   
        player = "Eva Longoria";   
    }   
  
    function getPlayer2() {   
        if (player === "Evan Longoria") {   
            player2 = "Derek Jeter";   
        } else {   
            player2 = "Teri Hatcher";   
        }
        return player2;  
    }   
    return getPlayer2();   
}   
  
alert(getPlayer());  
alert(getPlayer2());

< Back to Article