Get Programming with JavaScript - Listing 4.05
Listing 4.05 - Two more function definitions and assignments
var findTotal;
var displayMenu;
findTotal = function () {
result = number1 + number2;
};
displayMenu = function () {
console.log("Please choose an option:");
console.log("(1) Print log");
console.log("(2) Upload file");
console.log("(9) Quit");
};
Further Adventures
Listing 4.05 - Two more function definitions and assignments - Task 1
- Declare number1, number2 and result variables.
var findTotal;
var displayMenu;
var number1; // Declare variables
var number2;
var result;
findTotal = function () {
result = number1 + number2;
};
displayMenu = function () {
console.log("Please choose an option:");
console.log("(1) Print log");
console.log("(2) Upload file");
console.log("(9) Quit");
};
Listing 4.05 - Two more function definitions and assignments - Task 2
- Assign values to the number1 and number2 variables.
var findTotal;
var displayMenu;
var number1;
var number2;
var result;
// Assign values
number1 = 30;
number2 = 20;
findTotal = function () {
result = number1 + number2;
};
displayMenu = function () {
console.log("Please choose an option:");
console.log("(1) Print log");
console.log("(2) Upload file");
console.log("(9) Quit");
};
Listing 4.05 - Two more function definitions and assignments - Task 3
- Run the findTotal function by writing its name followed by parentheses: findTotal();
var findTotal;
var displayMenu;
var number1;
var number2;
var result;
number1 = 30;
number2 = 20;
findTotal = function () {
result = number1 + number2;
};
displayMenu = function () {
console.log("Please choose an option:");
console.log("(1) Print log");
console.log("(2) Upload file");
console.log("(9) Quit");
};
findTotal(); // Run the function
Running a function is also called calling or invoking the function.
Running the findTotal function doesn't produce any output. It calculates the sum of number1 and number2 and assigns the answer to the result variable.
Listing 4.05 - Two more function definitions and assignments - Task 4
- Display the result on the console.
var findTotal;
var displayMenu;
var number1;
var number2;
var result;
number1 = 30;
number2 = 20;
findTotal = function () {
result = number1 + number2;
};
displayMenu = function () {
console.log("Please choose an option:");
console.log("(1) Print log");
console.log("(2) Upload file");
console.log("(9) Quit");
};
findTotal();
console.log(result); // Display the result
Listing 4.05 - Two more function definitions and assignments - Task 5
- Run the displayMenu function.
var findTotal;
var displayMenu;
var number1;
var number2;
var result;
number1 = 30;
number2 = 20;
findTotal = function () {
result = number1 + number2;
};
displayMenu = function () {
console.log("Please choose an option:");
console.log("(1) Print log");
console.log("(2) Upload file");
console.log("(9) Quit");
};
findTotal();
console.log(result);
displayMenu(); // Run the displayMenu function