Variable Scope - Demo 1

This page produces a JavaScript error because the global context tries to access a variable that is in a separate context.

Here is the code:

var sport = "baseball";
var player = null;

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

getPlayer();

alert(player2);

< Back to Article