Functions and Control Flow Continued
Ever wondered how much 30% of 135 is? Well, wonder no more.
Our magical tool to find out is a function named percentageCalculator. Think of it as your personal number-crunching assistant, ready to calculate what any percentage of any number is. It's like asking a friend to do the maths for you, except this friend is super quick and never gets it wrong.
Task 1 - Percentage Calculator
Here's how we make it:
We create a function called
percentageCalculator.We provide it with two arguments: “number” and “percentage”. These are needed to perform the calculation.
Inside the function, we perform a mathematical operation to calculate the percentage of the number.
The function then returns the result of the calculation.
Finally, we call (invoke) our function with the arguments of 30 and 135. It then gives us our value back through the console.
// Percentage calculator function
// Here we will use the arrow function syntax
// Step 1: Define the function called 'percentageCalculator'.
const percentageCalculator = (number, percentage) => {
// Step 3: Inside the function, calculate the percentage of the number.
const result = (number * percentage) / 100;
// Step 4: Return the result of the calculation.
return `${result} is ${percentage}% of ${number}`;
};
// Step 5: Call the 'percentageCalculator' function with arguments 135 and 30, and log the result.
const result = percentageCalculator(135, 30);
console.log(result); // This will output the calculation result to the console.
// "40.5 is 30% of 135" will be logged to the console
Check out this live example on CodePen.
Let's take our percentageCalculator function and see it in action within a web page. A simple interface has been built using HTML, Bootstrap and CSS where users can input a number and a percentage to see the calculation performed live on the web page. This practical demonstration shows how the JavaScript function created above can be integrated into a real-world scenario, allowing for interactive user engagement.
By entering values into the provided fields, the application utilizes our percentageCalculator to compute and display the result directly on the page. This serves as a straightforward example of applying JavaScript functions in web development, illustrating the seamless interaction between HTML, CSS, and JavaScript in creating dynamic and interactive web applications.
See the code on CodePen.
Task 2 - Switch Statement
Next we'll tackle a scenario where customers can choose from three different drinks and three sizes. Whether it's a cola, lemonade, or orangeade, in small, medium, or large sizes, we've got a handy function to handle these choices seamlessly.
We introduce a function named drinkOrder that takes two arguments: one for the size of the drink and another for the type of drink (cola, lemon, or orange). The core of this function lies in its use of a switch statement, a powerful tool in JavaScript that steers the code in different directions based on the drink selected.
// Define the drinkOrder function with size and drink as parameters
const drinkOrder = (size, drink) => {
let requestedDrink = '';
// Use a switch statement to handle different drink types
switch (drink) {
case 'cola': // If the drink type is 'cola'
requestedDrink = 'Cola'; // Set the requestedDrink variable to 'Cola'
break; // Exit the switch statement
case 'lemon': // If the drink type is 'lemon'
requestedDrink = 'Lemonade'; // Set the requestedDrink variable to 'Lemonade'
break; // Exit the switch statement
case 'orange': // If the drink type is 'orange'
requestedDrink = 'Orangeade'; // Set the requestedDrink variable to 'Orangeade'
break; // Exit the switch statement
default: // If none of the cases match the drink type
return 'Drink not found'; // Return a 'Drink not found' message
}
// Return a message indicating the ordered drink size and type
return `You ordered a ${size} ${requestedDrink}`;
};
// Call the drinkOrder function with 'small' size and 'orange' drink type
const orderedDrink = drinkOrder('small', 'orange');
console.log(orderedDrink); // Log the result to the console
Check out this live example on CodePen.
Here's how it works: You start with the switch keyword, followed by the expression you want to evaluate (like a variable containing a drink type in our example). Inside the curly braces, you have multiple case statements, each representing a potential match for the expression's value. If the expression matches a case, the code block under that case runs. If none of the cases match, an optional default case can catch and handle these situations.
Let's take our drinkOrder function and see it in action within a web page. A simple interface has been built using HTML, Bootstrap and CSS where users can select a drink size and a drink and see the output live on the web page.
See the code on CodePen.
Again, the application utilizes our drinkOrder function to compute and display the output directly on the page. This serves as another straightforward example of applying JavaScript functions in web development.
Task 3 - Calculator
Finally, let's explore a versatile function called calculator that performs arithmetic operations on two numbers. This function accepts three arguments: two numbers and an operator (such as +, -, *, /, %). At its core, it utilizes the switch statement to direct the code to the appropriate operation based on the operator argument.
// Define the calculator function with three parameters: num1, num2, and operator
const calculator = (num1, num2, operator) => {
let value; // Initialize a variable to store the result
// Use a switch statement to handle different mathematical operations based on the operator
switch (operator) {
case '+': // If the operator is addition
value = num1 + num2; // Add num1 and num2, then assign this value to the value variable
break; // Exit the switch
case '-': // If the operator is subtraction
value = num1 - num2; // Subtract num2 from num1, then assign this value to the value variable
break; // Exit the switch
case '*': // If the operator is multiplication
value = num1 * num2; // Multiply num1 by num2, then assign this value to the value variable
break; // Exit the switch
case '/': // If the operator is division
if (num2 !== 0) { // Check if num2 is not zero to avoid division by zero
value = num1 / num2; // Divide num1 by num2, then assign this value to the value variable
} else {
return 'Cannot divide by zero'; // Return error message for division by zero
}
break; // Exit the switch
case '%': // If the operator is modulus
value = num1 % num2; // Get the remainder of num1 divided by num2, then assign this value to the value variable
break; // Exit the switch
default: // If the operator doesn't match any case
return 'Invalid operator'; // Return an error message for invalid operator
}
return value; // Return the value variable
};
// Example usage of the calculator function
const result = calculator(10, 5, '+'); // Call the calculator function
console.log(result); // Log the result to the console
// Will log 15 to the console
Check out this live example on CodePen.
This efficient approach allows calculator to swiftly determine and execute the required arithmetic operation. The switch statement's clear structure demonstrates the flexibility and utility of JavaScript for mathematical tasks.
Let's highlight the calculator function through a sleek calculator interface crafted with HTML and CSS. It uses the switch statement in our calculator function to handle user inputs: two numbers and an operation (add, subtract, multiply, divide, or modulus). Upon calculation, the function instantly displays the result, demonstrating JavaScript's ability to dynamically process and present data based on user interactions.
See the code on CodePen.