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

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

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

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

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);