How to Build a Calculator in an Interview
Calculator with basic operations and keyboard support. Here is how to build it.
How to Build a Calculator in an Interview
The calculator tests state management and event handling. Here is how to build it.
Requirements
- Display showing input and result.
- Number pad (0-9).
- Operations (+, -, *, /).
- Clear (C), equals (=), decimal (.).
- Keyboard support.
Plan (5 minutes)
- HTML: display, number pad, operations.
- State: current input, previous input, operation.
- Events: button click, keyboard input.
- Logic: perform calculation on equals.
Build Core (50 minutes)
HTML
<div class="calculator"> <input type="text" id="display" readonly /> <div class="buttons"> <button onclick="clearAll()">C</button> <button onclick="inputChar('7')">7</button> <button onclick="inputChar('8')">8</button> <button onclick="inputChar('9')">9</button> <button onclick="setOp('/')">/</button> <button onclick="inputChar('4')">4</button> <button onclick="inputChar('5')">5</button> <button onclick="inputChar('6')">6</button> <button onclick="setOp('*')">*</button> <button onclick="inputChar('1')">1</button> <button onclick="inputChar('2')">2</button> <button onclick="inputChar('3')">3</button> <button onclick="setOp('-')">-</button> <button onclick="inputChar('0')">0</button> <button onclick="inputChar('.')">.</button> <button onclick="calculate()">=</button> <button onclick="setOp('+')">+</button> </div> </div>
JavaScript
let current = "0"; let previous = null; let operation = null; function updateDisplay() { document.getElementById("display").value = current; } function inputChar(char) { if (current === "0" && char !== ".") current = char; else if (char === "." && current.includes(".")) return; else current += char; updateDisplay(); } function setOp(op) { if (operation) calculate(); previous = parseFloat(current); operation = op; current = "0"; } function calculate() { if (!operation || previous === null) return; const curr = parseFloat(current); let result; switch (operation) { case "+": result = previous + curr; break; case "-": result = previous - curr; break; case "*": result = previous * curr; break; case "/": result = curr === 0 ? "Error" : previous / curr; break; } current = String(result); operation = null; previous = null; updateDisplay(); } function clearAll() { current = "0"; previous = null; operation = null; updateDisplay(); }
Edge Cases (20 minutes)
- Division by zero (show "Error").
- Multiple decimals (prevent).
- Chaining operations (calculate before setting a new op).
- Keyboard support (0-9, +, -, *, /, =, Enter, Escape).
- Overflow (very large numbers).
Keyboard Support
document.addEventListener("keydown", (e) => { if (/[0-9]/.test(e.key)) inputChar(e.key); else if (["+", "-", "*", "/"].includes(e.key)) setOp(e.key); else if (e.key === "." ) inputChar("."); else if (e.key === "Enter" || e.key === "=") calculate(); else if (e.key === "Escape") clearAll(); });
The Takeaway
Build the calculator: HTML (display + buttons), JavaScript (state: current, previous, operation; input, setOp, calculate, clear), CSS (grid layout). Handle edge cases (division by zero, multiple decimals, chaining, keyboard). This tests state management and event handling.
Track current input, previous value, and operation. Number buttons append to current. Operation buttons store the operation and previous value. Equals performs the calculation. Clear resets everything. Use a grid layout for buttons.
Check if the divisor is 0 before dividing. If so, display 'Error' or 'Cannot divide by zero' instead of performing the calculation. Do not let JavaScript produce Infinity; handle it explicitly.
When a new operation is set and there is already a pending operation, calculate the pending operation first (calculate()), then store the result as the new previous and set the new operation. This allows chaining like 5 + 3 * 2.
Add a keydown listener. Map number keys to inputChar, operator keys to setOp, Enter/= to calculate, Escape to clear, and decimal to inputChar('.'). Prevent default for Enter to avoid form submission.
Division by zero (show Error), multiple decimals (prevent), chaining operations (calculate before setting new op), keyboard support, and overflow for very large numbers. Also handle the initial state (display 0).
Ready to master React completely?
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.
Master React
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course.

