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
- Use the showSum function to add 56 and 74.
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
- Create a showProduct function to multiply two numbers.
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
- Use your function to multiply three pairs of numbers.
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
- What about showDifference and showQuotient for subtraction and division?
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);