JavaScript Calculator Example

In this tutorial, I will tell you two ways to make a calculator using basic HTML, CSS and JavaScript. In first way we make functions for all operations and in the second we use some inbuilt global function to make a calculator. In both cases we are going to add some simple math operations like addition, subtraction, multiplication, division in our basic calculator. This project will help you to improve your logical ability and coding skills.

JavaScript Calculator Example

Method 1:

Mainly the functions that we need to work for calculator are handling the keypresses, inputting the digits, inputting the decimal point/key, handling operators, resisting the calculators, updating the display, equal key and clear key.

As we know calculator consists of keys and display. So, in the UI perspective we have to work on:

calculator tile – where we show the title

input buttons – where we display all keys

output screen – This is the screen where we can check what input we are entering and showing all the values that we entered.

Before starting this Project you must have knowledge or idea of these things:

  • if-else statements
  • javascript functions
  • arrow function
  • some operators like && and ||
  • change the text with the value attribute
  • add event listeners
  • querySelector
  • string methods like includes, contains etc.
  • eval function

So, coding part begins here for the first case. Initially, we have to make a div container in which we are going to add all buttons with proper styling. To make this UI we use CSS Grid box which is the best practice of writing proper responsive code. After this, we start work on functionalities.

Firstly we have to initialise the value of each variable and constant. Then we check what key is pressed by the user like operators, operands, decimal or clear according to this key we store it in different variables that we declared. So, when the user hits number keys then we store these values in operands. We define the separate function for each operation like inputting the digit, updating the display, decimal enter etc.

You can check the whole code below.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<style>
    
html {
  font-size: 62.5%;
  box-sizing: border-box;
}

*, *::before, *::after {
  margin: 0;
  padding: 0;
  box-sizing: inherit;
}

.calculator {
  border: 1px solid #ccc;
  border-radius: 5px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 400px;
}

.output-screen {
  width: 100%;
  font-size: 5rem;
  height: 80px;
  border: none;
  background-color: gray;
  color: #fff;
  text-align: right;
  padding-right: 20px;
  padding-left: 10px;
}

button {
  height: 60px;
  background-color: #fff;
  border-radius: 3px;
  border: 1px solid #c4c4c4;
  background-color: transparent;
  font-size: 2rem;
  color: #333;
  background-image: linear-gradient(to bottom,transparent,transparent 50%,rgba(0,0,0,.04));
  box-shadow: inset 0 0 0 1px rgba(255,255,255,.05), inset 0 1px 0 0 rgba(255,255,255,.45), inset 0 -1px 0 0 rgba(255,255,255,.15), 0 1px 0 0 rgba(255,255,255,.15);
  text-shadow: 0 1px rgba(255,255,255,.4);
}

button:hover {
  background-color: #eaeaea;
}

.operator {
  color: #337cac;
}

.clear-value {
  background-color: green;
  border-color: #b0353a;
  color: #fff;
}

.clear-value:hover {
  background-color: #f17377;
}

.calculate-value {
  background-color: blue;
  border-color: #337cac;
  color: #fff;
  height: 100%;
  grid-area: 2 / 4 / 6 / 5;
}

.calculate-value:hover {
  background-color: #4e9ed4;
}

.display-keys {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-gap: 20px;
  padding: 20px;
}
</style>
<body>
    <div class="calculator">
<h1 style="text-align: center;">Simple Javascript calculator</h1>
        <input type="text" class="output-screen" value="" disabled />
        
        <div class="display-keys">
          
          <button  class="operator" value="+">+</button>
          <button  class="operator" value="-">-</button>
          <button  class="operator" value="*">&times;</button>
          <button  class="operator" value="/">&divide;</button>
      
          <button  value="7">7</button>
          <button  value="8">8</button>
          <button  value="9">9</button>
      
      
          <button  value="4">4</button>
          <button  value="5">5</button>
          <button  value="6">6</button>
      
      
          <button  value="1">1</button>
          <button  value="2">2</button>
          <button  value="3">3</button>
      
      
          <button  value="0">0</button>
          <button  class="decimal" value=".">.</button>
          <button  class="clear-value" value="clear-value">AC</button>
      
          <button  class="calculate-value operator" value="=">=</button>
      
        </div>
      </div>
</body>
<script>

const calculator = {
  outputValue: '0',
  firstValue: null,
  flagForSecondOperand: false,
  operator: null,
}; 

function inputDigit(digit) {
  const { outputValue, flagForSecondOperand } = calculator;

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

function inputDecimal(dot) {
  if (calculator.flagForSecondOperand === true) return;
  
  // If the `outputValue` does not contain a decimal point
  if (!calculator.outputValue.includes(dot)) {
    // Append the decimal point
    calculator.outputValue += dot;
  }
}

function handleOperator(nextOperator) {
  const { firstValue, outputValue, operator } = calculator
  const inputValue = parseFloat(outputValue);

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

  if (firstValue == null) {
    calculator.firstValue = inputValue;
  } else if (operator) {
    const currentValue = firstValue || 0;
    const result = performCalculation[operator](currentValue, inputValue);

    calculator.outputValue = String(result);
    calculator.firstValue = result;
  }

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

const performCalculation = {
  '/': (firstValue, secondOperand) => (firstValue / secondOperand).toFixed(5),

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

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

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

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

function resetCalculator() {
  calculator.outputValue = '0';
  calculator.firstValue = null;
  calculator.flagForSecondOperand = false;
  calculator.operator = null;
}

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

updateDisplay();

const keys = document.querySelector('.display-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('decimal')) {
    inputDecimal(target.value);
    updateDisplay();
    return;
  }

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

  inputDigit(target.value);
  updateDisplay();
});

</script>
</html>

Simple JavaScript Calculator

Method 2:

We can also make a JavaScript calculator using the eval function. This function is used to evaluate any string. This is a built-in function of JS.

Here we used the table tag to make UI and for adding additional functions we use form HTML element. On each keypress, we put on click method to add that value to the output screen. And after this eval function evaluate all values when you click on any operator.

<form name="calculator">
  <table>
     <tr>
        <td colspan="4">
           <input type="text" name="display" id="display" disabled>
          
        </td>
     </tr>
     <tr>
           <td><input type="button" name="one" value="1" onclick="calculator.display.value += '1'"></td>
           <td><input type="button" name="two" value="2" onclick="calculator.display.value += '2'"></td>
           <td><input type="button" name="three" value="3" onclick="calculator.display.value += '3'"></td>
           <td><input type="button" class="operator" name="plus" value="+" onclick="calculator.display.value += '+'"></td>
    </tr>
    <tr>
           <td><input type="button" name="four" value="4" onclick="calculator.display.value += '4'"></td>
           <td><input type="button" name="five" value="5" onclick="calculator.display.value += '5'"></td>
           <td><input type="button" name="six" value="6" onclick="calculator.display.value += '6'"></td>
           <td><input type="button" class="operator" name="minus" value="-" onclick="calculator.display.value += '-'"></td>
    </tr>
    <tr>
           <td><input type="button" name="seven" value="7" onclick="calculator.display.value += '7'"></td>
           <td><input type="button" name="eight" value="8" onclick="calculator.display.value += '8'"></td>
           <td><input type="button" name="nine" value="9" onclick="calculator.display.value += '9'"></td>
           <td><input type="button" class="operator" name="times" value="x" onclick="calculator.display.value += '*'"></td>
    </tr>
    <tr>
    
           <td><input type="button" name="zero" value="0" onclick="calculator.display.value += '0'"></td>
           <td><input type="button" name="doit" value="=" onclick="calculator.display.value = eval(calculator.display.value)"></td>
          
      
        <td><input type="button" class="operator" name="div" value="." onclick="calculator.display.value += '.'"></td>
      <td><input type="button" class="operator" name="div" value="/" onclick="calculator.display.value += '/'"></td>
     </tr>
  </table>
              <input type="button" id="clear" name="clear" value="clear"  style="width:12%" onclick="calculator.display.value = ''">
</form>

Simple JavaScript Calculator

Comment down below if you have any queries related to javascript calculator.

1 thought on “JavaScript Calculator Example”

  1. 1. how to prevent multiple dot or operator(+,*,-,/) in row . ex 1+*!
    2. how to clear display after getting result when we click on digit for new calculation.
    3. how to calculate % using this formula = (firstvalue/100)*second value.
    4. how to differentiate the firstvalue and secondvalue after and before the operator. ex 100%50 = 50 , here 100 is firstvalue , 50 is secondvalue and after evaluating ans is 50

Leave a Comment

Your email address will not be published. Required fields are marked *