How to build a calculator in JavaScript

JavaScript is a versatile programming language that allows us to create dynamic and interactive web applications. Let's build a simple calculator using HTML, CSS, and JavaScript.

Step 1: Creating the HTML structure

The first step in building our calculator is to set up the HTML structure. We create a basic HTML template with a title, body, and a container div for our calculator. Inside the container div, we’ll have two main elements: the display and the buttons.

The <div class="calculator"> will be our container div, and we’ll place the calculator display and buttons inside it.

The calculator display will show the numbers and operations as users input them, and the buttons will allow users to interact with the calculator by entering numeric digits and performing basic arithmetic operations.

Here is the code for the HTML structure:

<!DOCTYPE html>
<html>
<head>
<title>Simple Calculator</title>
</head>
<body>
<div class="calculator">
<div class="display" id="display">0</div>
<div class="buttons">
<!-- Calculator buttons will be added here -->
</div>
</div>
</body>
</html>

Step 2: Adding calculator buttons

We will now add the buttons to our calculator. We’ll add the numeric digits, basic arithmetic operators, and special buttons to the <div class="buttons"> section.

Adding calculator buttons

Step 3: Styling the calculator

Now, we’ll add CSS styles to make our calculator visually appealing and user-friendly. We’ll use CSS to format the calculator container, display area, and buttons.

Step 3.1: Styling the calculator container

We start by styling the calculator container (<div class="calculator">). We set the width, add a border, round the corners with a border-radius, set a background color, and add some padding to create spacing inside the container. Additionally, we can apply a subtle box-shadow to give the calculator a slight elevation effect.

.calculator {
width: 300px;
border: 1px solid #ccc;
border-radius: 5px;
background-color: #fff;
padding: 10px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

Step 3.2: Styling the display

Next, we will style the calculator display (<div class="display">). The display will show the entered numbers, operations, results, or errors. We set the display height, font size, text alignment, add some padding, set a background color, add a border, and apply border-radius to create rounded corners. Additionally, we add a small margin at the bottom to create some separation between the display and the buttons.

.display {
height: 60px;
font-size: 24px;
text-align: right;
padding: 5px;
background-color: #f9f9f9;
border: 1px solid #ccc;
border-radius: 5px;
margin-bottom: 10px;
overflow: auto;
}

Step 3.3: Styling the buttons

Now, we will style the calculator buttons inside the <div class="buttons">. We will use CSS Grid to create a grid layout for the buttons, allowing them to be neatly arranged in rows and columns. Each button will have a fixed height and width, a comfortable font size, no borders, rounded corners, and a cursor that changes on hover to indicate clickability. We will also set a background color for the buttons and apply a slight color change on hover to enhance the interactive experience.

.buttons {
display: grid;
grid-template-columns: repeat(4, 3fr);
gap: 5px;
}
button {
height: 80px;
width: 70px;
font-size: 25px;
border: none;
border-radius: 5px;
cursor: pointer;
background-color: #f1f1f1;
}
button:hover {
background-color: #e1e1e1;
}

With the styles added, our calculator container, display, and buttons now have an organized layout. The display is set up to show numbers and operations in a right-aligned manner, and the buttons are styled to be responsive to user interaction.

Styling the calculator

Step 4: Initializing JavaScript variables

Now create a JavaScript file to start with the JavaScript part. We will initialize JavaScript variables and create functions to handle the calculator’s behavior. JavaScript will allow us to add interactivity to our calculator and perform calculations based on user input.

// Initialize variables to store the current display and result display state
let currentDisplay = "0"; // The current display content
let resultDisplay = false; // Flag to track whether the result is displayed

Step 5: Setting the display

Now, we need a function to append numbers and operators to the display area when the user clicks on the calculator buttons.

// Function to append a value to the current display
function appendToDisplay(value) {
if (currentDisplay === "0" || resultDisplay) {
// If the current display is "0" or the result is already displayed, replace it with the new value
currentDisplay = value;
} else {
// Otherwise, concatenate the new value to the current display
currentDisplay += value;
}
// Reset the result display flag to false, as the user entered a new value
resultDisplay = false;
// Update the calculator display to show the new content
updateDisplay();
}

Step 6: Updating the display

Create a function to update the display whenever a button is clicked or a calculation result is displayed.

// Function to update the calculator display with the current content
function updateDisplay() {
const displayElement = document.getElementById("display");
displayElement.textContent = currentDisplay;
}

Step 7: Calculating the result

To calculate the result when the = button is pressed, we will create a function that uses the JavaScript eval() function to evaluate the mathematical expression entered by the user. Then we will concatenate the result or error to display, call the updateDisplay to display the result and set the resultDisplay flag to true.

//Function to calculate and display the result
function calculateResult() {
try {
// Use the eval() function to evaluate the mathematical expression
const result = eval(currentDisplay);
// Append the result to the current display, preceded by an equal sign (=)
currentDisplay += "\n=" + result.toString();
// Update the calculator display with the result
updateDisplay();
} catch (error) {
// If there is an error in the expression (e.g., dividing by zero), display an error message
currentDisplay += "\nError";
// Update the calculator display to show the error message
updateDisplay();
}
// Set the result display flag to true to indicate that the result is displayed
resultDisplay = true;
}

Step 8: Clearing the last entry

We need a function to clear the last element entered when the CE (Clear Entry) button is pressed. This allows the user to remove the last number or operator if they make a mistake. We will use the slice method to slice off the last element and update the display.

// Function to clear the last element from the current display
function clearLastElement() {
// Remove the last character from the current display using the slice() method
currentDisplay = currentDisplay.slice(0, -1);
// If the current display becomes empty, set it back to "0"
if (currentDisplay === "") {
currentDisplay = "0";
}
// Update the calculator display to reflect the changes
updateDisplay();
}

Step 9: Clearing the display

To clear the entire display when the C (Clear) button is pressed, we will create a function to reset the calculator to its initial state and update the display.

//Function to clear the entire display
function clearDisplay() {
currentDisplay = "0"; // Reset the current display to "0"
resultDisplay = false; // Reset the result display flag to false
// Update the calculator display to show the cleared content
updateDisplay();
}

Step 10: Attaching event listeners

Now, let’s modify the HTML code to attach event listeners to the calculator buttons to trigger the appropriate functions when users click on them.

<!DOCTYPE html>
<html>
<head>
<title>Simple Calculator</title>
</head>
<body>
<div class="calculator">
<div class="display" id="display">0</div>
<div class="buttons">
<button onclick="appendToDisplay('(')">(</button>
<button onclick="appendToDisplay(')')">)</button>
<button onclick="clearLastElement()">CE</button>
<button onclick="clearDisplay()">C</button>
<button onclick="appendToDisplay('7')">7</button>
<button onclick="appendToDisplay('8')">8</button>
<button onclick="appendToDisplay('9')">9</button>
<button onclick="appendToDisplay('/')">/</button>
<button onclick="appendToDisplay('4')">4</button>
<button onclick="appendToDisplay('5')">5</button>
<button onclick="appendToDisplay('6')">6</button>
<button onclick="appendToDisplay('*')">*</button>
<button onclick="appendToDisplay('1')">1</button>
<button onclick="appendToDisplay('2')">2</button>
<button onclick="appendToDisplay('3')">3</button>
<button onclick="appendToDisplay('-')">-</button>
<button onclick="appendToDisplay('0')">0</button>
<button onclick="appendToDisplay('.')">.</button>
<button onclick="calculateResult()">=</button>
<button onclick="appendToDisplay('+')">+</button>
</div>
</div>
</body>
</html>

The calculator can now handle numeric input, perform basic arithmetic calculations, and display the results accordingly. Users can clear the display, clear the last element entered, and perform multiple calculations sequentially. You can further enhance this calculator by adding more advanced functionalities and improving the design.

Running the calculator

Place the HTML, CSS, and JavaScript code in appropriate files. Open the HTML file in the browser to interact with the calculator. Here is a sample calculator with basic operations of addition, subtraction, multiplication, and division:

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved