Skip to content

Simple Calculator

Easy ~25 min

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. 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. 2

    Set up state and select elements

    Declare a current string to hold the expression. Select the display and all buttons. The display always reflects current.

    Code
    let current = "0";
    const display = document.getElementById("display");
    const buttons = document.querySelectorAll("button");

    Expected result

    State is ready; display shows 0.

  3. 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.

    Code
    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;
      });
    });

    Expected result

    Clicking buttons builds and evaluates expressions.

  4. 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.

    Code
    function 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. 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.

    Code
    const 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

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 Lessons

  • Functions

    Functions for evaluation logic.

  • DOM

    Event handling for button clicks.

Related Practice

Related Cheatsheets

Related Glossary

Related Glossary

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to topic