Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
A simple calculator using JavaScript is a web-based tool that allows users to perform basic arithmetic operations such as addition, subtraction, multiplication, and division. It is commonly built using HTML for structure, CSS for styling, and JavaScript for functionality. This project is a great way to learn JavaScript, as it involves handling user input, performing calculations, and updating the UI dynamically.
In this article, we will create a simple calculator using JavaScript. We will learn how to take user input, process it using JavaScript functions, and display the results dynamically.
Approach to Create JavaScript Calculator
To build a simple calculator using JavaScript, we will follow these steps:
Create the HTML Structure - Design a user-friendly interface with buttons for numbers and operators.
Style with CSS - Make the calculator visually appealing.
Add JavaScript Functionality - Use JavaScript to handle button clicks, perform calculations, and display results.
Let's go through each step in detail.
1. Create the HTML Structure
First, we need an input field to display the result and buttons for digits and operations.
This JavaScript snippet allows users to input numbers and operations directly from the keyboard, making the calculator more user-friendly.
Example 1: Simple Calculator with if...else if...else
Building a simple calculator using `if...else if...else` statements is a beginner-friendly way to understand how conditional logic works in JavaScript. This approach checks the user’s input operation & performs the corresponding calculation based on the condition. Let’s discuss this in detail and how we can build this.
Step 1: Setting Up the HTML Structure
First, we need a basic HTML structure to create the calculator interface. This includes input fields for numbers, a dropdown or buttons for operations, & a button to display the result.
Two `<input>` fields (`num1` & `num2`) allow the user to enter numbers.
A `<select>` dropdown (`operation`) lets the user choose the operation.
A `<button>` triggers the `calculate()` function when clicked.
A `<span>` element (`result`) displays the calculated result.
Step 2: Writing the JavaScript Logic
Next, we’ll write the JavaScript code in a separate file (`calculator.js`) to handle the calculations using `if...else if...else` statements.
function calculate() {
// Get the input values
const num1 = parseFloat(document.getElementById('num1').value);
const num2 = parseFloat(document.getElementById('num2').value);
const operation = document.getElementById('operation').value;
let result;
// Perform the calculation based on the selected operation
if (operation === 'add') {
result = num1 + num2;
} else if (operation === 'subtract') {
result = num1 - num2;
} else if (operation === 'multiply') {
result = num1 num2;
} else if (operation === 'divide') {
if (num2 !== 0) {
result = num1 / num2;
} else {
result = 'Error: Division by zero';
}
} else {
result = 'Invalid operation';
}
// Display the result
document.getElementById('result').textContent = result;
}
Let’s see how the logic works:
1. The `calculate()` function is called when the user clicks the "Calculate" button.
2. It retrieves the values of `num1`, `num2`, & `operation` from the HTML elements.
3. Using `if...else if...else`, it checks the selected operation & performs the corresponding calculation.
4. If the user tries to divide by zero, it displays an error message.
5. Finally, the result is displayed in the `<span>` element with the ID `result`.
Step 3: Testing the Calculator
To test the calculator:
1. Open the HTML file in a browser.
2. Enter two numbers in the input fields.
3. Select an operation from the dropdown.
4. Click the "Calculate" button.
5. The result will be displayed below.
Example 2: Simple Calculator with switch
Using a `switch` statement to build a calculator is another efficient way to handle multiple conditions. The `switch` statement is often cleaner & more readable than multiple `if...else if...else` statements, especially when dealing with many conditions. Let’s build a simple calculator using the `switch` statement.
Step 1: Setting Up the HTML Structure
The HTML structure remains the same as in the previous example. We’ll reuse the same HTML code to keep things simple.
Now, let’s write the JavaScript code using the `switch` statement. We’ll replace the `if...else if...else` logic with a `switch` statement for better readability
function calculate() {
// Get the input values
const num1 = parseFloat(document.getElementById('num1').value);
const num2 = parseFloat(document.getElementById('num2').value);
const operation = document.getElementById('operation').value;
let result;
// Perform the calculation based on the selected operation
switch (operation) {
case 'add':
result = num1 + num2;
break;
case 'subtract':
result = num1 - num2;
break;
case 'multiply':
result = num1 num2;
break;
case 'divide':
if (num2 !== 0) {
result = num1 / num2;
} else {
result = 'Error: Division by zero';
}
break;
default:
result = 'Invalid operation';
}
// Display the result
document.getElementById('result').textContent = result;
}
Let’s discuss how the logic works:
1. The `calculate()` function is called when the user clicks the "Calculate" button.
2. It retrieves the values of `num1`, `num2`, & `operation` from the HTML elements.
3. The `switch` statement checks the value of `operation` & executes the corresponding case.
4. If the operation is `divide`, it also checks if `num2` is zero to avoid division by zero errors.
5. The `default` case handles any invalid operations.
6. Finally, the result is displayed in the `<span>` element with the ID `result`.
Step 3: Testing the Calculator
To test the calculator:
1. Open the HTML file in a browser.
2. Enter two numbers in the input fields.
3. Select an operation from the dropdown.
4. Click the "Calculate" button.
5. The result will be displayed below.
Frequently Asked Questions
How does eval() work in JavaScript?
The eval() function takes a string expression and evaluates it as JavaScript code. It is used here to perform calculations dynamically.
Can I customize the calculator further?
Yes! You can add more functionalities like square root, percentage, or memory functions using additional JavaScript functions.
How do I prevent errors in calculations?
Use try-catch blocks to handle invalid inputs and display an error message instead of crashing the program.
Conclusion
In this article, we built a simple calculator using JavaScript, HTML, and CSS. We learned how to create the user interface, style it, and add interactive functionalities with JavaScript. This project helps beginners understand DOM manipulation, event handling, and basic JavaScript operations. You can enhance it further by adding more features like history tracking and scientific functions.