Get Programming with JavaScript - Listing 3.11

Listing 3.11 - Using a property in a calculation

var player1; player1 = { name: "Max", score: 0 }; console.log(player1.name + " has scored " + player1.score); player1.score = player1.score + 50; console.log(player1.name + " has scored " + player1.score);

Further Adventures

Listing 3.11 - Using a property in a calculation - Task 1

var player1; player1 = { name: "Max", score: 0 }; console.log(player1.name + " has scored " + player1.score); player1.score = player1.score + 50; console.log(player1.name + " has scored " + player1.score); player1.score = player1.score * 1.1; // increase player1's score by 10%

Use the * symbol to multiply numbers together. Multiply a number by 1.1 to increase it by 10%.

Listing 3.11 - Using a property in a calculation - Task 2

var player1; var player2; // declare a second variable player1 = { name: "Max", score: 0 }; player2 = { // create a second name: "Kandra", // player and assign score: 40 // it to the player2 }; // variable console.log(player1.name + " has scored " + player1.score); player1.score = player1.score + 50; console.log(player1.name + " has scored " + player1.score); player1.score = player1.score * 1.1;

Listing 3.11 - Using a property in a calculation - Task 3

var player1; var player2; player1 = { name: "Max", score: 0 }; player2 = { name: "Kandra", score: 40 }; console.log(player1.name + " has scored " + player1.score); player1.score = player1.score + 50; console.log(player1.name + " has scored " + player1.score); player1.score = player1.score * 1.1; // Log a message including the sum of scores console.log("The sum of scores for " + player1.name + " and " + player2.name + " is " + (player1.score + player2.score));

The + symbol does double-duty: it concatenates strings and it adds numbers. Use parentheses to ensure the numbers are added before the result is concatenated to the string.

See what happens if you remove the parentheses around player1.score + player2.score.