Table of contents
1.
Introduction
2.
Approach to Create JavaScript Calculator
2.1.
1. Create the HTML Structure
2.2.
2. Style with CSS
2.3.
3. Add JavaScript Functionality
3.
Example : Dynamic JavaScript Calculator using HTML, CSS, and JavaScript
4.
Example 1: Simple Calculator with if...else if...else
4.1.
Step 1: Setting Up the HTML Structure
4.2.
Step 2: Writing the JavaScript Logic
4.3.
Step 3: Testing the Calculator
5.
Example 2: Simple Calculator with switch
5.1.
Step 1: Setting Up the HTML Structure
5.2.
Step 2: Writing the JavaScript Logic
5.3.
Step 3: Testing the Calculator
6.
Frequently Asked Questions
6.1.
How does eval() work in JavaScript?
6.2.
Can I customize the calculator further?
6.3.
How do I prevent errors in calculations?
7.
Conclusion
Last Updated: Feb 9, 2025
Easy

Simple Calculator Using JavaScript

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

A simple calculator using JavaScript is a web-based tool that allows users to perform basic arithmetic operations such as addition, subtraction, multiplication, and division. It is commonly built using HTML for structure, CSS for styling, and JavaScript for functionality. This project is a great way to learn JavaScript, as it involves handling user input, performing calculations, and updating the UI dynamically.

Simple Calculator Using JavaScript

In this article, we will create a simple calculator using JavaScript. We will learn how to take user input, process it using JavaScript functions, and display the results dynamically. 

Approach to Create JavaScript Calculator

To build a simple calculator using JavaScript, we will follow these steps:

  1. Create the HTML Structure - Design a user-friendly interface with buttons for numbers and operators.
     
  2. Style with CSS - Make the calculator visually appealing.
     
  3. Add JavaScript Functionality - Use JavaScript to handle button clicks, perform calculations, and display results.

Let's go through each step in detail.

1. Create the HTML Structure

First, we need an input field to display the result and buttons for digits and operations.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple Calculator</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="calculator">
        <input type="text" id="display" disabled>
        <div class="buttons">
            <button onclick="clearDisplay()">C</button>
            <button onclick="appendValue('1')">1</button>
            <button onclick="appendValue('2')">2</button>
            <button onclick="appendValue('+')">+</button>
            <button onclick="appendValue('3')">3</button>
            <button onclick="appendValue('4')">4</button>
            <button onclick="appendValue('-')">-</button>
            <button onclick="appendValue('5')">5</button>
            <button onclick="appendValue('6')">6</button>
            <button onclick="appendValue('*')">*</button>
            <button onclick="appendValue('7')">7</button>
            <button onclick="appendValue('8')">8</button>
            <button onclick="appendValue('/')">/</button>
            <button onclick="appendValue('9')">9</button>
            <button onclick="appendValue('0')">0</button>
            <button onclick="calculateResult()">=</button>
        </div>
    </div>
    <script src="script.js"></script>
</body>
</html>

2. Style with CSS

Now, let's add some CSS to improve the calculator's appearance.

body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #f4f4f4;
}

.calculator {
    background-color: white;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    text-align: center;
}

#display {
    width: 100%;
    height: 50px;
    text-align: right;
    font-size: 24px;
}

.buttons button {
    width: 60px;
    height: 60px;
    font-size: 18px;
    margin: 5px;
}

3. Add JavaScript Functionality

Finally, we will add JavaScript to handle the button clicks and perform calculations.

let display = document.getElementById("display");
function appendValue(value) {
    display.value += value;
}
function clearDisplay() {
    display.value = "";
}

function calculateResult() {
    try {
        display.value = eval(display.value);
    } catch (error) {
        display.value = "Error";
    }
}


Output

Output

Now, when you click the buttons, the input field updates with the selected number or operator, and clicking = evaluates the expression.

Example : Dynamic JavaScript Calculator using HTML, CSS, and JavaScript

In this example, we will improve the calculator by adding more features like decimal point support and keyboard input handling.

document.addEventListener("keydown", function(event) {
    if ((event.key >= '0' && event.key <= '9') || ['+', '-', '*', '/'].includes(event.key)) {
        appendValue(event.key);
    } else if (event.key === 'Enter') {
        calculateResult();
    } else if (event.key === 'Backspace') {
        display.value = display.value.slice(0, -1);
    }
});

 

This JavaScript snippet allows users to input numbers and operations directly from the keyboard, making the calculator more user-friendly.

Example 1: Simple Calculator with if...else if...else

Building a simple calculator using `if...else if...else` statements is a beginner-friendly way to understand how conditional logic works in JavaScript. This approach checks the user’s input operation & performs the corresponding calculation based on the condition. Let’s discuss this in detail and how we can build this.

Step 1: Setting Up the HTML Structure

First, we need a basic HTML structure to create the calculator interface. This includes input fields for numbers, a dropdown or buttons for operations, & a button to display the result.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Simple Calculator</title>
</head>
<body>
  <h1>Simple Calculator</h1>
  <input type="number" id="num1" placeholder="Enter first number">
  <input type="number" id="num2" placeholder="Enter second number">
  <select id="operation">
    <option value="add">Addition (+)</option>
    <option value="subtract">Subtraction (-)</option>
    <option value="multiply">Multiplication ()</option>
    <option value="divide">Division (/)</option>
  </select>
  <button onclick="calculate()">Calculate</button>
  <h2>Result: <span id="result"></span></h2>


  <script src="calculator.js"></script>
</body>
</html>


Output

Output

In this code:

  • Two `<input>` fields (`num1` & `num2`) allow the user to enter numbers.
     
  • A `<select>` dropdown (`operation`) lets the user choose the operation.
     
  • A `<button>` triggers the `calculate()` function when clicked.
     
  • A `<span>` element (`result`) displays the calculated result.

Step 2: Writing the JavaScript Logic

Next, we’ll write the JavaScript code in a separate file (`calculator.js`) to handle the calculations using `if...else if...else` statements.

function calculate() {
  // Get the input values
  const num1 = parseFloat(document.getElementById('num1').value);
  const num2 = parseFloat(document.getElementById('num2').value);
  const operation = document.getElementById('operation').value;
  let result;

  // Perform the calculation based on the selected operation
  if (operation === 'add') {
    result = num1 + num2;
  } else if (operation === 'subtract') {
    result = num1 - num2;
  } else if (operation === 'multiply') {
    result = num1  num2;
  } else if (operation === 'divide') {
    if (num2 !== 0) {
      result = num1 / num2;
    } else {
      result = 'Error: Division by zero';
    }
  } else {
    result = 'Invalid operation';
  }

  // Display the result
  document.getElementById('result').textContent = result;
}


Let’s see how the logic works:

1. The `calculate()` function is called when the user clicks the "Calculate" button.
 

2. It retrieves the values of `num1`, `num2`, & `operation` from the HTML elements.
 

3. Using `if...else if...else`, it checks the selected operation & performs the corresponding calculation.
 

4. If the user tries to divide by zero, it displays an error message.
 

5. Finally, the result is displayed in the `<span>` element with the ID `result`.

Step 3: Testing the Calculator

To test the calculator:

1. Open the HTML file in a browser.
 

2. Enter two numbers in the input fields.
 

3. Select an operation from the dropdown.
 

4. Click the "Calculate" button.
 

5. The result will be displayed below.

Example 2: Simple Calculator with switch

Using a `switch` statement to build a calculator is another efficient way to handle multiple conditions. The `switch` statement is often cleaner & more readable than multiple `if...else if...else` statements, especially when dealing with many conditions. Let’s build a simple calculator using the `switch` statement.

Step 1: Setting Up the HTML Structure

The HTML structure remains the same as in the previous example. We’ll reuse the same HTML code to keep things simple.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Simple Calculator</title>
</head>
<body>
  <h1>Simple Calculator</h1>
  <input type="number" id="num1" placeholder="Enter first number">
  <input type="number" id="num2" placeholder="Enter second number">
  <select id="operation">
    <option value="add">Addition (+)</option>
    <option value="subtract">Subtraction (-)</option>
    <option value="multiply">Multiplication ()</option>
    <option value="divide">Division (/)</option>
  </select>
  <button onclick="calculate()">Calculate</button>
  <h2>Result: <span id="result"></span></h2>


  <script src="calculator.js"></script>
</body>
</html>


Output

Output

Step 2: Writing the JavaScript Logic

Now, let’s write the JavaScript code using the `switch` statement. We’ll replace the `if...else if...else` logic with a `switch` statement for better readability

function calculate() {
  // Get the input values
  const num1 = parseFloat(document.getElementById('num1').value);
  const num2 = parseFloat(document.getElementById('num2').value);
  const operation = document.getElementById('operation').value;
  let result;

  // Perform the calculation based on the selected operation
  switch (operation) {
    case 'add':
      result = num1 + num2;
      break;
    case 'subtract':
      result = num1 - num2;
      break;
    case 'multiply':
      result = num1  num2;
      break;
    case 'divide':
      if (num2 !== 0) {
        result = num1 / num2;
      } else {
        result = 'Error: Division by zero';
      }
      break;
    default:
      result = 'Invalid operation';
  }
  // Display the result
  document.getElementById('result').textContent = result;
}


Let’s discuss how the logic works:

1. The `calculate()` function is called when the user clicks the "Calculate" button.
 

2. It retrieves the values of `num1`, `num2`, & `operation` from the HTML elements.
 

3. The `switch` statement checks the value of `operation` & executes the corresponding case.
 

4. If the operation is `divide`, it also checks if `num2` is zero to avoid division by zero errors.
 

5. The `default` case handles any invalid operations.
 

6. Finally, the result is displayed in the `<span>` element with the ID `result`.

Step 3: Testing the Calculator

To test the calculator:

1. Open the HTML file in a browser.
 

2. Enter two numbers in the input fields.
 

3. Select an operation from the dropdown.
 

4. Click the "Calculate" button.
 

5. The result will be displayed below.

Frequently Asked Questions

How does eval() work in JavaScript?

The eval() function takes a string expression and evaluates it as JavaScript code. It is used here to perform calculations dynamically.

Can I customize the calculator further?

Yes! You can add more functionalities like square root, percentage, or memory functions using additional JavaScript functions.

How do I prevent errors in calculations?

Use try-catch blocks to handle invalid inputs and display an error message instead of crashing the program.

Conclusion

In this article, we built a simple calculator using JavaScript, HTML, and CSS. We learned how to create the user interface, style it, and add interactive functionalities with JavaScript. This project helps beginners understand DOM manipulation, event handling, and basic JavaScript operations. You can enhance it further by adding more features like history tracking and scientific functions.

Live masterclass