Simple Calculator
What you'll build
A calculator page with a display area and buttons for digits 0-9, operations (+, −, ×, ÷), equals, and clear. Clicking buttons builds an expression and shows the result.
Goals
- Build a calculator UI with buttons
- Handle digit and operator button clicks
- Evaluate the expression and display the result
- Clear and reset the calculator state
Prerequisites
- Functions and conditionals
- DOM selection and event listeners
- String concatenation
Steps
- 1
Create the HTML structure
Create a display div and buttons for digits 0-9, four operators, equals, and clear. Use data attributes to mark each button's role.
Code<div id="display">0</div> <button data-value="7">7</button> <button data-value="8">8</button> <button data-value="+">+</button> <button data-value="=">=</button> <button data-action="clear">C</button>Expected result
A display showing 0 and calculator buttons appear.
- 2
Set up state and select elements
Declare a
currentstring to hold the expression. Select the display and all buttons. The display always reflectscurrent.Codelet current = "0"; const display = document.getElementById("display"); const buttons = document.querySelectorAll("button");Expected result
State is ready; display shows 0.
- 3
Handle button clicks
Add a click listener to each button. If it is the clear button, reset to '0'. If it is equals, evaluate the expression. Otherwise, append the value to the current expression.
Codebuttons.forEach(btn => { btn.addEventListener("click", () => { const action = btn.dataset.action; const value = btn.dataset.value; if (action === "clear") { current = "0"; } else if (value === "=") { try { current = String(eval(current)); } catch { current = "Error"; } } else { current = current === "0" ? value : current + value; } display.textContent = current; }); });Expected result
Clicking buttons builds and evaluates expressions.
Hint
eval() is used here for simplicity. In production, use a proper expression parser.
- 4
Add input validation & error handling
Add validation at user input points: check for empty values, non-numbers, negatives, and other anomalies, using try/catch or conditionals to show friendly messages. Robust JS programs don't crash on unexpected input.
Codefunction safeParse(value) { if (value === null || value === undefined || value === "") { throw new Error("Input is empty"); } const num = Number(value); if (Number.isNaN(num)) { throw new Error(`"${value}" is not a valid number`); } return num; } try { const n = safeParse(userInput); process(n); } catch (err) { console.error(err.message); }Expected result
Empty or non-number input shows an error message instead of crashing; valid numbers process normally.
- 5
Add event listeners & interaction
Bind event listeners (click, input, keydown, etc.) to page elements so the program responds to user actions. Interactivity is the core value of JavaScript in the front end.
Codeconst button = document.querySelector("#action-btn"); const input = document.querySelector("#user-input"); button.addEventListener("click", () => { const value = input.value.trim(); if (!value) return; runMainLogic(value); }); input.addEventListener("keydown", (e) => { if (e.key === "Enter") button.click(); });Expected result
Clicking the button or pressing Enter triggers the main logic; empty input is ignored.
Try it yourself
<div id="display">0</div>
<!-- TODO: add digit, operator, equals, and clear buttons -->
<script>
// TODO: set up state, select buttons, handle clicks
</script><div id="display">0</div>
<button data-value="7">7</button>
<button data-value="8">8</button>
<button data-value="9">9</button>
<button data-value="/">÷</button>
<button data-value="4">4</button>
<button data-value="5">5</button>
<button data-value="6">6</button>
<button data-value="*">×</button>
<button data-value="1">1</button>
<button data-value="2">2</button>
<button data-value="3">3</button>
<button data-value="-">−</button>
<button data-value="0">0</button>
<button data-value=".">.</button>
<button data-value="=">=</button>
<button data-value="+">+</button>
<button data-action="clear">C</button>
<script>
let current = "0";
const display = document.getElementById("display");
const buttons = document.querySelectorAll("button");
buttons.forEach(btn => {
btn.addEventListener("click", () => {
const action = btn.dataset.action;
const value = btn.dataset.value;
if (action === "clear") {
current = "0";
} else if (value === "=") {
try { current = String(eval(current)); } catch { current = "Error"; }
} else {
current = current === "0" ? value : current + value;
}
display.textContent = current;
});
});
</script>What you learned
You built a working calculator by managing expression state in a string, handling button events, and evaluating the result — the core pattern behind every interactive calculator app.
Related Resources
Related Practice
- Predict the Function Call Result
Practice predicting function results.
Related Cheatsheets
- JavaScript Cheatsheet
DOM and event syntax reference.
Related Glossary
- Function
Reusable code blocks.
- Event Listener
Handling click events.
Related Glossary
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
- Function
Reusable code blocks.
- Event Listener
Handling click events.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.