Calculator with Vanilla JavaScript
Tags: html, css, javascript
Published: 2020-06-01 21:02:23

I will like to share how I made a simple calculator with JavaScript.

The calculator can perform basic arithmetic operations like addition, subtraction, multiplication and division of numbers.


Here is how I did it:

**Step 1: Stored my selectors in variables to target the DOM elements**
```javascript
const erase = document.querySelector("#erase");
const user = document.querySelector("#user");
const ops = document.getElementsByClassName("ops");
const equals = document.querySelector(".equals_to");
const num = document.getElementsByClassName("num");
const period = document.getElementById("period");
```

**Step 2: Declare global variables**

I declared variables and assigned them their initial values.
``` javascript
let currentNum = ""; //to store clicked number
let operator = null; //initial value of the operator
let calculation = []; //array to store the numbers and operators
let previousNum = ""; //to store the last calculated result
```

**Step 3: Function structure**

Functions to update and calculate the numbers.
```javascript
// To update the button number
const updateNum = (e) => {
} 
// To select and update operator
const selectOperator = (e) => {
} 
// To calculate the result
const getResult = (e) => {
} 
```

**Step 4: Onclick event listeners**

I assigned functions accordingly to the elements onclick
```javascript
for ( i = 0; i<num.length; i++) {
  num[i].addEventListener('click', updateNum);
}
for (let i = 0; i<ops.length; i++) {
  ops[i].addEventListener('click', selectOperator);
}

equals.addEventListener('click', getResult);
}
```

**Step 5: Functions to store clicked numbers**

To declare a variable to store the user clicked input;
```javascript
const numText = e.target.innerText;
```
To first check if operator is null and previousNum has a value. If true, clear previousNum value;

```javascript
const updateNum = (e) => {
  if (operator === "" && previousNum !== ""){
  previousNum = "";
  }
```
Also check if number clicked is a decimal, and confirm that currentNum does not already have a decimal. If true if does, set numText to null. 
```javascript
else if (numText === "." && currentNum.includes ('.')) {
   numText = null;
 }
```
Lastly check if numText is decimal and currentNum has no stored value. If true, set currentNum to 0;

```javascript
if (currentNum === "" && numText === ".") {
    currentNum = "0.";
 user.innerHTML = currentNum;
```
now, append the value of numText to currentNum ; 
```javascript
else {
  currentNum += numText;
 user.innerHTML = currentNum;
 }
}
```

Declared an operator to take the text content of the button operator clicked
If the last value of the array is not equal to an operator, let operator be push to the array string;

**Step 6: Functions to store operator clicked**

First check if previousNum is empty, if it isn't, push the value to the calculation array, and clear previousNum empty. Then check the last value of the calculation array, if it is not an operator, push the operator to the array;
```javascript
const selectOperator = (e) => {

if (previousResult !== "") {
    calculation.push(previousResult);
    if (calculation[calculation.length - 1] !== ("+" || "-" || "/" || "*")) {
      operator = e.target.innerText;
      calculation.push(operator);
    }
    previousResult = "";
  }
}
```

Next, check if currentNum has a value, if yes, push the value to the calculation array. Then check the last value of the calculation array, if it is not an operator, push the operator to the array;
```javascript
 if (currentNum !== "") {
    calculation.push(currentNum);
    if (calculation[calculation.length - 1] !== ("+" || "-" || "/" || "*")) {
      operator = e.target.innerText;
      calculation.push(operator);
    }
  }
```
then clear currentNum
```javascript
currentNum=""; 
```

**Step 7: Function to carry out the calculation**

This will be triggered when the equal button is clicked
First check if currentNum has a value. If yes, add the value to the calculation array. Then carry out the calculation;

```javascript
function getResult(e) {
  if (currentNum !== "") {
    calculation.push(currentNum);
  }
  var result = eval(calculation.join("")).toString();

  user.innerHTML = result;
  previousResult = result;
  currentNum = "";
  calculation = [];
  operator = null;
}
```

**Step 8: Erase function**

Onclick of the erase button, set all variable to their initial values;
```javascript
erase.onclick = () => {
user.innerHTML = "0";
currentNum = "";
pendingNum = "";
calculation = [];
}
```
You can view the full working code on:
{% codepen https://codepen.io/tolulope-esther/pen/GRogMEO default-tab=js,result %}
Alright! I hope this brief article helped to build your own calculator. Thanks for reading and happy coding! I'm opened to questions and suggestions.