Variable Scope - Demo 4

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.

Additionally, it correctly displays the value of the "player2" variable twice, the first time when it is accessed directly inside the first function. That variable is not directly accessible outside that function.

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;   
    }   
    alert(getPlayer2());   
    return getPlayer2();   
}   
  
alert(getPlayer());   
alert(getPlayer2());

< Back to Article