Get Programming with JavaScript - Listing 5.06

Listing 5.06 - A function with two arguments

var showSum; showSum = function (number1, number2) { var total = number1 + number2; console.log("The sum is " + total); }; showSum(30, 23); showSum(2.8, -5);

Further Adventures

Listing 5.06 - A function with two arguments - Task 1

var showSum; showSum = function (number1, number2) { var total = number1 + number2; console.log("The sum is " + total); }; showSum(30, 23); showSum(2.8, -5); showSum(56, 74); // Call the function with two arguments

Listing 5.06 - A function with two arguments - Task 2

var showSum; var showProduct; // Declare a variable showSum = function (number1, number2) { var total = number1 + number2; console.log("The sum is " + total); }; // Define a function // Assign it to the variable showProduct = function (number1, number2) { // Include two parameters var product = number1 * number2; console.log("The product is " + product); }; showSum(30, 23); showSum(2.8, -5); showSum(56, 74);

Listing 5.06 - A function with two arguments - Task 3

var showSum; var showProduct; showSum = function (number1, number2) { var total = number1 + number2; console.log("The sum is " + total); }; showProduct = function (number1, number2) { var product = number1 * number2; console.log("The product is " + product); }; showSum(30, 23); showSum(2.8, -5); showSum(56, 74); showProduct(10, 10); showProduct(2.8, -5); showProduct(0.5, 50);

Listing 5.06 - A function with two arguments - Task 4

var showDifference; var showQuotient; showDifference = function (number1, number2) { var difference = number1 - number2; console.log("The difference is " + difference); }; showQuotient = function (number1, number2) { var quotient = number1 / number2; console.log("The quotient is " + quotient); }; showDifference(10, 6); showDifference(6, 10); showQuotient(10, 2);

Our showDifference function always subtracts the second number from the first. This could lead to negative differences.

The Math.abs function can be used to give the absolute value of the answer. It leaves positive numbers alone but converts negative numbers to positive numbers. Math.abs(5) is 5. Math.abs(-5) is 5.

var showDifference; showDifference = function (number1, number2) { var difference = Math.abs(number1 - number2); console.log("The difference is " + difference); }; showDifference(6, 10);