Get Programming with JavaScript - Listing 6.04
Listing 6.04 - Returning the sum of two numbers
var add;
add = function (number1, number2) {
var total = number1 + number2;
return total;
};
var sum = add(50, 23);
console.log(sum);
Further Adventures
Listing 6.04 - Returning the sum of two numbers - Task 1
- Find and display the sum of a different pair of numbers.
var add;
add = function (number1, number2) {
var total = number1 + number2;
return total;
};
var sum = add(500, -123); // find the sum
console.log(sum); // display the sum
Listing 6.04 - Returning the sum of two numbers - Task 2
- Change the call to console.log so that the display on the console reads: 'The sum of 50 and 23 is 73' using the add function to generate the answer.
var add;
add = function (number1, number2) {
var total = number1 + number2;
return total;
};
var sum = add(50, 23);
// Update the message logged to the console
console.log("The sum of 50 and 23 is " + sum);
Listing 6.04 - Returning the sum of two numbers - Task 3
- Can you use the add function as it is to add more than two numbers?
var add;
add = function (number1, number2) {
var total = number1 + number2;
return total;
};
// add three numbers
var sum = add(18, add(50, 23));
console.log("The sum of 18, 50 and 23 is " + sum);
Remember the return value replaces the function call, so add(18, add(50, 23))
becomes add(18, 73)
which becomes 91
.
Listing 6.04 - Returning the sum of two numbers - Task 4
- Create a function to return the sum of three numbers given as arguments.
var add;
var add3; // declare a variable
add = function (number1, number2) {
var total = number1 + number2;
return total;
};
// define a function and
// assign it to your variable
add3 = function (number1, number2, number3) {
return add(number1, add(number2, number3));
};
var sum = add3(18, 50, 23);
console.log("The sum of 18, 50 and 23 is " + sum);
Of course it would be easier just to add the numbers directly.
var add3;
add3 = function (number1, number2, number3) {
return number1 + number2 + number3;
};
var sum = add3(18, 50, 23);
console.log("The sum of 18, 50 and 23 is " + sum);