/calculator

A simple calculator built entirely in vanilla JS.

Primary LanguageJavaScript

JavaScript Calculator 📱

Check out the Live Demo Here

js-calculator

The Design 🔷

The Calculator was designed with a mobile-first approach, using a css-grid layout and styled using the Glass Morphism design trend.

The Logic 🔶

The calculator consists of:

  • A display section where users will be able to see the operations and their result
  • 7 Operators: Addition, Subtraction, Multiplication, Division, Percentage, Square root & Power of
  • Numbers from 0 to 9
  • 4 Additional buttons:
    • Equal button that will return the result of the operation
    • Delete button to allow user to delete one or multiple digits
    • Dot (.) button to allow user to use decimal units
    • C button to activate the function All Clear and allow user to reset the calculator

The Code 🔳

The values of the users' inputs (when they click on a button for each single digit) will be stored in two variables with empty arrays. let firstOperand = []; and let secondOperand = [];

A 3rd variable, will take a value of true. let isFirstOperandFilled = true;

An undefined variable for the operators. let operator;

Getting the Values:

An EventListener, followed by an if statement function was set up, so that the values of the buttons will be pushed into the first variable array, using array.push() until the user selects one of the 7 operators. Once a user has selected an operator, the variable isFirstOperandFilled will be set to false, causing every other value from the following buttons' inputs to be pushed into our second array variable.

Deleting the Values:

To delete values, we simply reverse the logic used to originally get the values. This time, we are deleting items from the array so we will use array.pop() to delete the last value inserted into the array.

Calculation

switch cases will evaluate different scenarios and based on that, different mathematical operations will be performed:

switch (operandCheck) {
       case operandCheck && operator.includes('+'):
            result = +firstOperand + +secondOperand;
            display.innerHTML += ` =  <span class="final-result">${result}</span> `;
            break;
       case operandCheck && operator.includes('-'):
            result = +firstOperand - +secondOperand;
            display.innerHTML += ` =  <span class="final-result">${result}</span> `;
            break;
       [...]
}