JavaScript Program to Make a Simple Calculator

In this tutorial, we'll create a simple calculator using JavaScript that can perform basic arithmetic operations: addition, subtraction, multiplication, and division.

We'll use the prompt() function for input and switch statement to handle different operations.

Here's the full code for the calculator:

Calculator code

// Function to perform calculations
function calculator() {
  // Prompt the user to select an operation
  const operator = prompt('Enter operator (+, -, *, /):');

  // Prompt the user to enter the numbers
  const num1 = parseFloat(prompt('Enter the first number:'));
  const num2 = parseFloat(prompt('Enter the second number:'));

  let result;

  // Use a switch statement to perform the selected operation
  switch (operator) {
    case '+':
      result = num1 + num2;
      break;
    case '-':
      result = num1 - num2;
      break;
    case '*':
      result = num1 * num2;
      break;
    case '/':
      if (num2 !== 0) {
        result = num1 / num2;
      } else {
        result = 'Error: Division by zero is not allowed!';
      }
      break;
    default:
      result = 'Invalid operator! Please refresh and try again.';
  }

  // Display the result
  console.log(`Result: ${result}`);
}

// Call the calculator function
calculator();

Explanation of the Code

Define the calculator Function:

The entire program is wrapped in a function called calculator. This is a good practice for modular and reusable code.

Prompt for Operation:

const operator = prompt(‘Enter operator (+, -, *, /):');
This line prompts the user to input the desired arithmetic operation (+, -, *, or /).
The input is stored in the variable operator.

Prompt for Numbers:

const num1 = parseFloat(prompt(‘Enter the first number:'));
const num2 = parseFloat(prompt(‘Enter the second number:'));
These lines prompt the user to input two numbers.
The parseFloat() function converts the string input from prompt() to a floating-point number, allowing for decimal operations.

Variable for the Result:

let result;
Declares a variable result to store the outcome of the selected operation.

Switch Statement for Operation Selection:

switch (operator) { … }

This block decides which arithmetic operation to perform based on the user's input.
Each case corresponds to a different operator:
+: Adds num1 and num2.
-: Subtracts num2 from num1.
*: Multiplies num1 by num2.
/: Divides num1 by num2 and includes a check to prevent division by zero.
break; statements ensure that once a case is executed, the program exits the switch block.
The default case handles invalid operator input by setting the result to an error message.

Display the Result:

console.log(\Result: ${result}`);`
Displays the result of the operation in the console using template literals.

Call the calculator Function:

calculator();

This line invokes the calculator function, starting the program.

Example Usage

When you run this program, it will:
Ask for an operator (e.g., +, -, *, /).
Ask for two numbers.
Perform the operation and log the result in the console.

Sample Run

Enter operator (+, -, *, /): +
Enter the first number: 10
Enter the second number: 5
Result: 15

Future Enhancements

Input Validation: Add checks to ensure that the inputs are valid numbers before performing operations.
User Interface: Create a more interactive user interface using HTML and buttons instead of prompt() for a better user experience.
Additional Operations: Add more mathematical operations, like modulus (%), exponentiation (**), square root, etc.

This code provides a simple yet effective way to perform basic arithmetic operations using JavaScript. The use of prompt() and switch statement makes it easy to understand and extend.

Feel free to modify and expand this code for more complex calculator functionalities!

Related posts

10 JavaScript conversion programs covering various scenarios

JavaScript Program to Check for a Leap Year

JavaScript Program to Generate a Random Number