Get Programming with JavaScript - Listing 5.11
Listing 5.11 - Displaying a player's location
var showPlayerPlace;
showPlayerPlace = function (playerName, playerPlace) {
console.log(playerName + " is in " + playerPlace);
};
showPlayerPlace("Kandra", "The Dungeon of Doom");
showPlayerPlace("Dax", "The Old Library");
Further Adventures
Listing 5.11 - Displaying a player's location - Task 1
- Inside the console.log parentheses, change playerName to playerName[0]
var showPlayerPlace;
showPlayerPlace = function (playerName, playerPlace) {
console.log(playerName[0] + " is in " + playerPlace);
};
showPlayerPlace("Kandra", "The Dungeon of Doom");
showPlayerPlace("Dax", "The Old Library");
The playerName variable has been assigned a string, the name of a player.
The square brackets on the end of the variable name allow us to access a single character in the string.
The index in the square brackets is zero-based. That means that an index of zero corresponds to the first character. playerName[0] will give the first letter in the player's name.
Listing 5.11 - Displaying a player's location - Task 2
- Change the number in the brackets to 1.
var showPlayerPlace;
showPlayerPlace = function (playerName, playerPlace) {
console.log(playerName[1] + " is in " + playerPlace);
};
showPlayerPlace("Kandra", "The Dungeon of Doom");
showPlayerPlace("Dax", "The Old Library");
playerName[1] will give the second letter in the player's name. (Remember the index is zero-based.)
Listing 5.11 - Displaying a player's location - Task 3
- What happens when you change the number to 3? Why?
var showPlayerPlace;
showPlayerPlace = function (playerName, playerPlace) {
console.log(playerName[3] + " is in " + playerPlace);
};
showPlayerPlace("Kandra", "The Dungeon of Doom");
showPlayerPlace("Dax", "The Old Library");
playerName[3] will give the fourth letter in the player's name. (Remember the index is zero-based.)
ERROR! - But "Dax" only has three letters. You can't access the fourth letter of a string with only three characters.