Practice Function Implementation
In this step, you'll practice implementing functions by creating a small program that demonstrates various function techniques. We'll build a simple calculator application to reinforce your understanding of function implementation.
Open the WebIDE and create a new file called calculator.js
in the ~/project
directory. We'll implement several mathematical functions:
// Function to add two numbers
function add(a, b) {
return a + b;
}
// Function to subtract two numbers
function subtract(a, b) {
return a - b;
}
// Function to multiply two numbers
function multiply(a, b) {
return a * b;
}
// Function to divide two numbers with error handling
function divide(a, b) {
if (b === 0) {
return "Error: Division by zero";
}
return a / b;
}
// Function to calculate the square of a number
function square(x) {
return x * x;
}
// Demonstrate calculator functions
console.log("Addition: 5 + 3 =", add(5, 3));
console.log("Subtraction: 10 - 4 =", subtract(10, 4));
console.log("Multiplication: 6 * 7 =", multiply(6, 7));
console.log("Division: 15 / 3 =", divide(15, 3));
console.log("Square of 4 =", square(4));
console.log("Division by zero:", divide(10, 0));
When you run this code, you'll see the following output:
Example output:
Addition: 5 + 3 = 8
Subtraction: 10 - 4 = 6
Multiplication: 6 * 7 = 42
Division: 15 / 3 = 5
Square of 4 = 16
Division by zero: Error: Division by zero
Key points about function implementation:
- Create functions with clear, single responsibilities
- Use parameters to make functions flexible
- Implement error handling when necessary
- Test your functions with different inputs
- Use meaningful function and variable names
Try experimenting by adding more mathematical functions or modifying the existing ones.