Calculators

A calculator is a great way to learn the basics of a programming language.

Students can start calculator using HTML, CSS, and JavaScript. The calculator project will introduce coder to basic user interface design and key event handling in JavaScript.


Code Overview

🔹 HTML Structure

The calculator is organized with <div> elements:

  • calculator-container: Holds all buttons and the display.
  • calculator-output: Shows the current number or result.
  • Rows of buttons: Each row contains numbers or operations (+, -, *, /, =).
  • Special buttons: A/C clears the calculator, = performs the calculation.

This structure makes the calculator easy to understand visually and connects each button to JavaScript logic.

🔹 JavaScript State

The calculator uses variables to track what’s happening:

  • firstNumber: Stores the first number entered.
  • operator: Stores which operation (+, -, *, /) is chosen.
  • nextReady: A flag that tells the calculator whether to start fresh with a new number or keep appending digits.

These variables act like the calculator’s memory.


🔹 Event Listeners

Event listeners connect user actions to code:

  • Number buttons: Call number() to update the display.
  • Operation buttons: Call operation() to store the operator and prepare for the next number.
  • Equals button: Runs calculate() to get the result.
  • Clear button: Resets everything back to zero.

This is how the calculator responds to clicks and user input.

// Number buttons
numbers.forEach(button => {
  button.addEventListener("click", () => {
    number(button.textContent);
  });
});


🔹 Calculation Logic

The calculate() function decides what math to perform:

  • Uses a switch statement to check the operator.
  • + adds the numbers.
  • - subtracts the numbers.
  • * and / currently show “TODO” — students will implement these.

This design makes it clear where new operations can be added.

function calculate(first, second) {
  switch (operator) {
    case "+":
      return first + second;
    case "-":
      return first - second;
    case "*":


Hacks

Try these challenges to extend your calculator:

  1. Hack 1: Implement Multiplication
    • Add logic for * in the calculate() function.
    • Hint: Use first * second.
  2. Hack 2: Implement Division
    • Add logic for / in the calculate() function.
    • Hint: Use first / second.
    • Bonus: Handle division by zero (show an error instead of crashing).
  3. Hack 3: Add Keyboard Support
    • Listen for keydown events.
    • Map keys like +, -, *, /, Enter, and numbers to the calculator functions.
  4. Hack 4: Style the Calculator
    • Change button colors, adjust spacing, or redesign the layout.
    • Try making the calculator theme match your site.
  5. Hack 5: Add a New Operation
    • Extend the calculator with something new, like square root () or percentage (%).
    • Add a button in the HTML and logic in the calculate() function.