JavaScript calculator is a web application that allows a user to perform basic mathematical operations such as addition, subtraction, multiplication, division, and more complex operations such as exponents, percentages, and square roots. JavaScript is the most popular scripting language for creating web pages and web applications and is used in all modern web browsers. In this article, we will explore how to create a JavaScript calculator with code examples.
Creating a Basic Calculator
The first step in creating a JavaScript calculator is to create the HTML and CSS that will define the look and feel of the calculator. In this example, we will create a simple calculator that looks like this:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Calculator</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="calculator">
<input type="text" id="result" readonly>
<button onclick="clearResult()">C</button>
<button onclick="deleteLast()">CE</button>
<button onclick="calculate('+')">+</button>
<button onclick="calculate('')"></button>
<button onclick="calculate('*')">*</button>
<button onclick="calculate('/')">/</button>
<button onclick="calculate('%')">%</button>
<button onclick="calculate('**')">^</button>
<button onclick="calculate('sqrt')">sqrt</button>
<button onclick="calculate('=')">=</button>
<button onclick="addNumber(0)">0</button>
<button onclick="addNumber(1)">1</button>
<button onclick="addNumber(2)">2</button>
<button onclick="addNumber(3)">3</button>
<button onclick="addNumber(4)">4</button>
<button onclick="addNumber(5)">5</button>
<button onclick="addNumber(6)">6</button>
<button onclick="addNumber(7)">7</button>
<button onclick="addNumber(8)">8</button>
<button onclick="addNumber(9)">9</button>
<button onclick="addNumber('.')">.</button>
</div>
<script src="script.js"></script>
</body>
</html>
In this HTML code, we have created a set of buttons and an input field to receive input from the user. Each button is assigned an onclick event handler that will execute a JavaScript function when clicked.
The CSS for this calculator will define the size and position of the elements on the page. Here is the CSS for this calculator:
#calculator {
border: solid 1px black;
width: 200px;
height: 240px;
margin: 0 auto;
textalign: center;
}
#result {
width: 100%;
height: 50px;
fontsize: 24px;
}
button {
width: 33.33%;
height: 40px;
fontsize: 20px;
backgroundcolor: #4CAF50;
color: white;
border: none;
margin: 0;
padding: 0;
float: left;
}
button:lastchild {
width: 100%;
}
button:hover {
backgroundcolor: #3e8e41;
cursor: pointer;
}
With the HTML and CSS in place, we can now focus on the JavaScript code that will make the calculator work.
The JavaScript Code
The JavaScript code for this calculator will have three main functions:

addNumber(): This function will add a number to the calculator display.

calculate(): This function will perform the mathematical operation on the numbers that are on the calculator display.

clearResult(): This function will reset the calculator display.
Here is the JavaScript code for this calculator:
let currentResult = ''; // the current number on the display
let operator = ''; // the operator used for the calculation
let result = 0; // the result of the calculation
let decimalPoint = false; // tracks whether a decimal point has been entered
// add a number to the display
function addNumber(number) {
if (decimalPoint && number === '.') {
return;
} else if (number === '.') {
decimalPoint = true;
}
currentResult += number;
document.getElementById('result').value = currentResult;
}
// perform the calculation
function calculate(newOperator) {
decimalPoint = false; // reset the decimal point counter
if (newOperator === '=') { // if the user presses equal sign, perform the calculation
switch (operator) {
case '+':
result += Number(currentResult);
break;
case '':
result = Number(currentResult);
break;
case '*':
result *= Number(currentResult);
break;
case '/':
result /= Number(currentResult);
break;
case '%':
result = (result / 100) * Number(currentResult);
break;
case '**':
result = Math.pow(result, Number(currentResult));
break;
case 'sqrt':
result = Math.sqrt(Number(currentResult));
break;
default:
result = Number(currentResult);
break;
}
currentResult = '';
operator = '';
document.getElementById('result').value = result;
} else { // if the user presses any other operator, update the operator and store the current number on display
operator = newOperator;
if (result === 0) {
result = Number(currentResult);
} else {
switch (operator) {
case '+':
result += Number(currentResult);
break;
case '':
result = Number(currentResult);
break;
case '*':
result *= Number(currentResult);
break;
case '/':
result /= Number(currentResult);
break;
case '%':
result = (result / 100) * Number(currentResult);
break;
case '**':
result = Math.pow(result, Number(currentResult));
break;
case 'sqrt':
result = Math.sqrt(Number(currentResult));
break;
default:
break;
}
currentResult = '';
document.getElementById('result').value = result;
}
}
}
// clear the display
function clearResult() {
decimalPoint = false;
currentResult = '';
operator = '';
result = 0;
document.getElementById('result').value = '';
}
// delete the last digit on the display
function deleteLast() {
currentResult = currentResult.slice(0, 1);
document.getElementById('result').value = currentResult;
}
In this code, we have created four variables: currentResult, operator, result, and decimalPoint. The currentResult variable stores the number that is currently on the calculator display. The operator variable stores the operator used for the calculation. The result variable stores the result of the calculation. The decimalPoint variable is used to track whether a decimal point has been entered.
The addNumber() function adds a number to the calculator display. If a decimal point is already entered, it will return without adding another decimal point. The calculate() function performs the mathematical operation on the numbers that are on the calculator display. If the user presses the equal sign, it performs the calculation, and if the user presses any other operator, it updates the operator and stores the current number on display. The clearResult() function resets the calculator display. The deleteLast() function removes the last digit on the calculator display.
Conclusion
In this article, we have learned how to create a simple JavaScript calculator with code examples. The calculator works by allowing the user to enter numbers and operators and performs a calculation based on input given by the user. This calculator is fully functional and can be modified as per your need. You can add more advanced mathematical functions depending on your requirement and make it a fullfledged scientific calculator. With the knowledge, you can use your web development skills to build calculators for your own website or for your clients.
here are some additional information and tools that you may find useful when working on a JavaScript calculator:

Math Object: JavaScript's Math object provides a set of methods that can be used to perform more advanced mathematical operations beyond the basic arithmetic calculations that a simple calculator can do. For example, the Math object includes methods for computing the sine, cosine, and tangent of an angle, as well as rounding to the nearest integer or selecting a random number. You can incorporate these Math functions to extend the functionality of your calculator.

Libraries: JavaScript libraries such as Math.js, Big.js, and Decimal.js can simplify calculations while providing more precise results. These libraries offer various features and functions to make complex mathematical operations easier to perform.

Keyboard Support: A calculator that supports keyboard input can make calculations faster and more efficient for users. For example, users can use the numeric keypad to enter numbers and the enter key to execute calculations.

Commandline Calculator: A commandline calculator lets you perform calculations without using a graphical interface. Node.js offers the ability to create commandline applications with JavaScript, including a commandline calculator that can be executed in a terminal or command prompt.

Unit Converter: A unit converter can be integrated with a calculator to allow users to convert units of measurement such as temperature, distance, weight, and volume. For instance, you can create a button that triggers a dropdown with unit options and do conversions using the base unit.
When building your JavaScript calculator, make sure to test your implementation thoroughly to ensure proper functionality and accuracy of the results. Remember that a calculator is a tool that needs to be reliable and accurate, as incorrect calculations can have significant consequences. By incorporating these techniques into your coding practices, you should be able to build a fully functional calculator with a smooth user experience.
Popular questions
 What is a JavaScript calculator?
A JavaScript calculator is a web application that allows users to perform basic mathematical operations such as addition, subtraction, multiplication, division, percentages, square roots and more. It is written in the JavaScript programming language and runs on web browsers.
 What are the main functions of a JavaScript calculator?
The main functions of a JavaScript calculator are to perform mathematical calculations on user input and display the result of the calculation. A calculator may also have functions like clearing the display, deleting the last entered number and using memory functions like addition and subtraction.
 What does the Math Object do in JavaScript?
The Math object in JavaScript provides a set of methods that can be used to perform more advanced mathematical operations beyond the basic arithmetic calculations that a simple calculator can do. For example, the Math object includes methods for computing the sine, cosine, and tangent of an angle, as well as rounding to the nearest integer or selecting a random number.
 What are some popular JavaScript libraries for implementing a calculator?
Some popular JavaScript libraries for implementing a calculator include Math.js, Big.js, and Decimal.js. These libraries provide various features and functions to make complex mathematical operations easier to perform while providing more precise results.
 What are some additional features that can be added to a JavaScript calculator?
Additional features that can be added to a JavaScript calculator include keyboard support, a commandline interface, unit conversion functions, scientific functions and more. These features enhance the calculator's functionality and make calculations faster and more efficient for users.
Tag
CalcJS