// Function to perform basic arithmetic operations
function calculate(a, b, operator) {
switch (operator) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
default:
return 'Invalid operator';
}
}
// Example: Perform addition (10 + 5)
const result = calculate(10, 5, '+');
console.log('Calculator Result:', result);
code
Simple Calculator
This JavaScript code defines a function calculate that performs basic arithmetic operations (addition, subtraction, multiplication, and division) based on the provided operator. The example performs addition (10 + 5), and the result is logged to the console. The comments provide explanations for each part of the code.
Calculator
Switch Statement
Basic Arithmetic