Updated April 6, 2023
Introduction to JavaScript Calculator
The Basic intention at the end of this article is to create a simple calculator with the help of JavaScript which can perform all the basic arithmetic operations. Only the key is a valid expression should be passed via input keys to see the results on the output screen.
An Example is: 42 + 15
In order to build a valid expression, we should be informed about few things i.e. the first input (42), the second input (15) and the operator pressed (+).
Hence, we’ll start with building an object ‘CALC’ which will keep info about all the above three things.
const calc = {
dispValue: '0',
firstInput: null,
waitForSecondInput: false,
operator: null,
};
The CALC object have all the necessary attributes to check whether a valid expression is passed. Here, dispValue will hold the string value to be shown on the screen, firstInput will hold the first input value, waitForSecondInput is a flag that will check whether the expression is fine or another input needs to be entered, and operator attribute will hold value of operator.
How to Build a JavaScript Calculator?
How to build a javascript calculator? are explain below:
Updating the Display Screen
Initially, the calculator screen will show nothing. We need to pull the value of dispValue attribute on the calculator screen which should be ‘0’ by default. In order to perform the above operation well, we will define a function which will update the value of the screen with the dispValue content. This function will be called whenever there is a need to change the display content within the app.
function updateDisp() {
const disp = document.querySelector('.calc-screen');
disp.value = calc.dispValue;
}
updateDisp();
Managing the Key Presses
Usually in calculator’s keys are in the following 4 sets: operators (+, -, *, /, =), numbers(0-9), a reset key (AC), and a decimal (.) key. Now we’ll check and find out which key was clicked.
const keys = document.querySelector('.calc-keys');
keys.addEventListener('click', (event) => {
const { choosen } = event;
if (! choosen.matches('button')) {
return;
}
if (choosen.classList.contains('operator')) {
console.log('operator', choosen.value);
return;
}
if (choosen.classList.contains('decimal')) {
Console.log('decimal', choosen.value);
return;
}
if (choosen.classList.contains('all-clear')) {
Console.log('clear', choosen.value);
return;
}
console.log('number', choosen.value);
});
Here, we put a listener for a click event on .calc-keys. This will filter us to the button clicked since all the keys are the children nodes of the element. In the event listener’s callback function, we scratch out the property of the event and unpack these object properties into distinctive variables. The chosen variable which represents the element which was clicked. If it is not a button (i.e spaces within the adjacent buttons), we’ll exit the function immediately.
Updating the Screen with the Digits
Here we will visualize the input digits of the user on the calculator screen.
function inputNumber(number) {
const { dispValue, waitForSecondInput } = calc;
if (waitForSecondInput === true) {
calc.dispValue = number;
calc.waitForSecondInput = false;
} else {
calc.dispValue = dispValue === '0' ? number : dispValue + number;
}
console.log(calc);
}
Next, replace console.log('number', choosen.value); in the eventlistener block with the following:
inputNumber(choosen.value);
updateDisp();
Handling a Decimal Key
Whenever the decimal key is pressed, we need to check if there is already a decimal present on the screen if yes then second decimal should not be added otherwise add the decimal after the series of number on the display of the calculator.
function inputDecimal(val) {
// Only If the `dispValue` does not contain a decimal point append the decimal
if (!calc.dispValue.includes(val)) {
calc.dispValue += val;
}
}
Then replace console.log(‘decimal’, choosen.value); in the eventlistener block with the following code:
inputDecimal(choosen.value);
updateDisp();
Managing the Operators
When the user enters the first input and presses any operator:
This stimulates us that the user is all set to input the second number. Hence now we need to save the first number provided by the user and update the calculator display with the relevant number.
function manageOperator(Oper) {
const { firstInput, dispValue, operator } = calc
const input = parseFloat(dispValue);
if (firstInput === null) {
calc.firstInput = input;
}
calc.waitForSecondInput = true;
calc.operator = Oper;
}
Then replace console.log(‘operator’, choosen.value) in the eventlistener block with the following code:
handleOperator(choosen.value);
updateDisplay();
When the user enters the first input and presses any operator:
Now the second case is when the user has pressed the second input number and after that an operator button is pressed. So now we have all the values for a valid expression hence we’ll calculate the result and store it in the firstInput attribute and display it on the calculator screen.
Here we are storing the value in firstInput attribute because the user can also use another operator on the result provided hence for further calculation this part is needed.
Now we’ll modify the function manageOperator accordingly:
function manageOperator(Oper) {
const { firstInput, dispValue, operator } = calc
const input = parseFloat(dispValue);
if (firstInput == null) {
calc.firstInput = input;
} else if (operator) {
const output = performCalc[operator](firstInput, input);
calc.dispValue = String(output);
calc.firstInput = output;
}
calc.waitForSecondInput = true;
calc.operator = Oper;
console.log(calc);
}
Then we’ll create a new object named as performCalc below manageOperator with the listed attributes:
const performCalc = {
'/': (firstInput, secondInput) => firstInput / secondInput,
'*': (firstInput, secondInput) => firstInput * secondInput,
'+': (firstInput, secondInput) => firstInput + secondInput,
'-': (firstInput, secondInput) => firstInput - secondInput,
'=': (firstInput, secondInput) => secondInput
};
The else if statement attached to manageOperator Function validates if an operator is present already. If yes, then property lookup is executed for the particular operator in the performCalc object and the function matching the operator is then executed.
Output:
Conclusion
This is an exert for making a good working calculator with the help of JavaScript. The HTML and CSS part needs to be written separately for the look and feel part of the app. The above calculator can be made more realistic with adding further functionalities such as when the user enters two operators what to do then, adding operators such as % can make it more like of your android or iPhone like calculator app.
Recommended Articles
This is a guide to JavaScript Calculator. Here we also discuss the definition and Top 4 Versions of CodeIgniter along with an explanation. You may also have a look at the following articles to learn more –