PUBLISHED ON: MARCH 15, 2023
JavaScript Program to make a Simple Calculator
A calculator is a tool that is extensively used for completing mathematical operations. It is a need in our daily lives. We will build a JavaScript function that can execute basic mathematical operations such as addition, subtraction, multiplication, and division in this program. The function accepts two operands and an operator as inputs, executes the associated operation on the operands, and returns the result.
The application is designed to be basic and straightforward to comprehend, making it an excellent starting point for those new to JavaScript. We also have an interactive JavaScript course where you can learn JavaScript from basics to advanced and get certified. Check out the course and learn more from here.
Approach:
This approach is very simple using the if else if loop in each case we check for Addition, Subtraction, Multiplication, or Division.
Program to make a Simple Calculator
// JavaScript program for a Simple Calculator
const operator = prompt('Enter operator ( either +, -, * or / ): ');
const num1 = parseFloat(prompt('Enter first number: '));
const num2 = parseFloat(prompt('Enter second number: '));
let result;
if (operator == '+')
result = num1 + num2;
else if (operator == '-')
result = num1 - num2;
else if (operator == '/')
result = num1 / num2;
else
result = num1 * num2;
console.log(num1 + " " +operator+" " +num2 " = " result);
Enter operator ( either +, -, * or / ): +
Enter first number: 4.6
Enter second number: 3.4
4.6 + 3.4 = 8.00
Conclusion
Finally, we created a JavaScript program capable of performing basic mathematical operations such as addition, subtraction, multiplication, and division. The program receives two operands and an operator as inputs, then performs the corresponding operation on the operands and returns the result based on the operator.
This program is a good place to start if you're new to JavaScript programming and want to learn the fundamentals of working with variables, functions, and conditional statements. It can also be used as a foundation for more advanced calculators that can handle a broader range of operations or more complex inputs.