How to make a calculator in JavaScript

"Create a calculator in JavaScript with an example: use variables, prompt and alert to create a basic calculator for basic operations."

Creating a Calculator in JavaScript

Creating a calculator in JavaScript is a relatively simple task. You can create a basic calculator by using HTML, CSS, and JavaScript. JavaScript will be used to handle the calculations, while HTML and CSS will provide the framework and styling. Here is an example of how to create a simple calculator in JavaScript.

HTML

<div class="calculator">
  <input type="text" readonly="readonly" class="calculator-screen" value="0" />
  <div class="calculator-keys">
    <button type="button" class="operator" value="+">+</button>
    <button type="button" class="operator" value="-">-</button>
    <button type="button" class="operator" value="*">&times;</button>
    <button type="button" class="operator" value="/">&divide;</button>
    <button type="button" class="number" value="7">7</button>
    <button type="button" class="number" value="8">8</button>
    <button type="button" class="number" value="9">9</button>
    <button type="button" class="number" value="4">4</button>
    <button type="button" class="number" value="5">5</button>
    <button type="button" class="number" value="6">6</button>
    <button type="button" class="number" value="1">1</button>
    <button type="button" class="number" value="2">2</button>
    <button type="button" class="number" value="3">3</button>
    <button type="button" class="number" value="0">0</button>
    <button type="button" class="clear" value="clear">C</button>
    <button type="button" class="equal-sign operator" value="=">=</button>
  </div>
</div>

The HTML code above creates a simple calculator with all the necessary buttons. The <input> tag is used to create the calculator screen, while the <div> tag is used to create the calculator buttons. Each button is given a class that specifies its type (e.g. number, operator, etc.).

CSS

.calculator {
  width: 225px;
  margin: 0 auto;
  padding: 20px 20px 9px;
  background-color: #9dd2ea;
  border-radius: 9px;
  box-shadow: 1px 2px 5px rgba(0, 0, 0, 0.3);
}

.calculator-screen {
  width: 100%;
  height: 40px;
  padding: 10px;
  background-color: #3d3d3d;
  color: white;
  font-size: 2rem;
  text-align: right;
  border: none;
  border-radius: 5px;
  box-shadow: 1px 2px 5px rgba(0, 0, 0, 0.3);
}

.calculator-keys {
  width: 225px;
  display: grid;
  grid-template-columns: repeat(4, 25%);
  grid-gap: 5px;
  padding: 10px;
  box-shadow: 1px 2px 5px rgba(0, 0, 0, 0.3);
}

.calculator-keys button {
  font-size: 2rem;
  width: 100%;
  height: 50px;
  background-color: #9dd2ea;
  color: #333;
  border: none;
  border-radius: 5px;
  box-shadow: 1px 2px 5px rgba(0, 0, 0, 0.3);
  cursor: pointer;
}

.calculator-keys button:hover {
  background-color: #3d3d3d;
  color: white;
}

.operator {
  background-color: #ffa834;
  color: white;
}

.operator:hover {
  background-color: #f7a91d;
}

.clear {
  background-color: #ff5e5e;
  color: white;
}

.clear:hover {
  background-color: #f54d4d;
}

The CSS code above styles the calculator. It sets the size, background color, and font size of the calculator and the buttons. It also adds hover effects to the buttons when the mouse is hovering over them.

JavaScript

<script>
  let calculator = {
    displayValue: '0',
    firstOperand: null,
    waitingForSecondOperand: false,
    operator: null
  };

  function inputDigit(digit) {
    const { displayValue, waitingForSecondOperand } = calculator;

    if (waitingForSecondOperand === true) {
      calculator.displayValue = digit;
      calculator.waitingForSecondOperand = false;
    } else {
      calculator.displayValue = displayValue === '0' ? digit : displayValue + digit;
    }
  }

  function inputDecimal(dot) {
    if (calculator.waitingForSecondOperand === true) return;

    if (!calculator.displayValue.includes(dot)) {
      calculator.displayValue += dot;
    }
  }

  function handleOperator(nextOperator) {
    const { firstOperand, displayValue, operator } = calculator;
    const inputValue = parseFloat(displayValue);

    if (operator && calculator.waitingForSecondOperand)  {
      calculator.operator = nextOperator;
      return;
    }

    if (firstOperand === null) {
      calculator.firstOperand = inputValue;
    } else if (operator) {
      const result = performCalculation[operator](firstOperand, inputValue);

      calculator.displayValue = String(result);
      calculator.firstOperand = result;
    }

    calculator.waitingForSecondOperand = true;
    calculator.operator = nextOperator;
  }

  const performCalculation = {
    '/': (firstOperand, secondOperand) => firstOperand / secondOperand,

    '*': (firstOperand, secondOperand) => firstOperand * secondOperand,

    '+': (firstOperand, secondOperand) => firstOperand + secondOperand,

    '-': (firstOperand, secondOperand) => firstOperand - secondOperand,

    '=': (firstOperand, secondOperand) => secondOperand
  };

  function resetCalculator() {
    calculator.displayValue = '0';
    calculator.firstOperand = null;
    calculator.waitingForSecondOperand = false;
    calculator.operator = null;
  }

  function updateDisplay() {
    const display = document.querySelector('.calculator-screen');
    display.value = calculator.displayValue;
  }

  updateDisplay();

  const keys = document.querySelector('.calculator-keys');
  keys.addEventListener('click', (event) => {
    const { target } = event;
    if (!target.matches('button')) {
      return;
    }

    if (target.classList.contains('operator')) {
      handleOperator(target.value);
      updateDisplay();
      return;
    }

    if (target.classList.contains('clear')) {
      resetCalculator();
      updateDisplay();
      return;
    }

    inputDigit(target.value);
    updateDisplay();
  });
</script>

The JavaScript code above handles all the logic for the calculator. It starts by defining an object called calculator which will store the data for the calculator. The inputDigit() function is used to update the display value when a number button is clicked. The inputDecimal() function is used to add a decimal point to the display value. The handleOperator() function is used to perform the calculations and store the result. The performCalculation() function is a lookup table that contains the different calculations that can be performed. The resetCalculator() function is used to reset the calculator to its default state. Finally, the updateDisplay() function is used to update the display with the current value stored in the calculator object.

By combining HTML, CSS, and JavaScript, you can create a basic calculator in JavaScript. This example can be extended to create a more advanced calculator with additional features.

Answers (0)