Building a Basic Calculator Using JavaScript

Jul 26, 2024

Understanding Calculator Functionality

Before diving into the code, it is essential to understand the basic functionality of a calculator. A calculator typically includes the following features:

  1. Input Fields: These are the fields where the user enters the numbers and operators.

  2. Display: This is the area where the results of the calculations are displayed.

  3. Operators: These are the mathematical operators (+, -, *, /) that perform the calculations.

  4. Clear Button: This button clears the input fields and the display.

  5. Equals Button: This button performs the calculation and displays the result.

HTML Structure

To create the basic structure of our calculator, we need to define the HTML elements. Here is the HTML structure for our calculator:

<!DOCTYPE html>
<html>
<head>
    <title>Basic Calculator</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }
        .calculator {
            width: 200px;
            height: 250px;
            border: 1px solid #ccc;
            padding: 10px;
            text-align: center;
            font-size: 18px;
        }
        .input-field {
            width: 100%;
            height: 30px;
            border: 1px solid #ccc;
            padding: 10px;
            font-size: 16px;
        }
        .button {
            width: 30%;
            height: 30px;
            background-color: #4CAF50;
            color: #fff;
            border: none;
            padding: 10px;
            font-size: 16px;
            cursor: pointer;
        }
        .button:hover {
            background-color: #3e8e41;
        }
    </style>
</head>
<body>
    <div class="calculator">
        <input type="text" class="input-field" id="display" readonly>
        <button class="button" id="clear">C</button>
        <button class="button" id="divide">/</button>
        <button class="button" id="multiply">*</button>
        <button class="button" id="subtract">-</button>
        <button class="button" id="add">+</button>
        <button class="button" id="equals">=</button>
        <button class="button" id="zero">0</button>
        <button class="button" id="decimal">.</button>
        <button class="button" id="one">1</button>
        <button class="button" id="two">2</button>
        <button class="button" id="three">3</button>
        <button class="button" id="four">4</button>
        <button class="button" id="five">5</button>
        <button class="button" id="six">6</button>
        <button class="button" id="seven">7</button>
        <button class="button" id="eight">8</button>
        <button class="button" id="nine">9</button>
    </div>
    <script src="calculator.js"></script>
</body>
</html>

JavaScript Code

Now, let's dive into the JavaScript code that will make our calculator functional. We will create acalculator.jsfile and add the following code:

const display = document.getElementById('display');
const buttons = document.querySelectorAll('.button');
const operators = ['+', '-', '\*', '/'];

buttons.forEach((button) => {
    button.addEventListener('click', (e) => {
        const value = e.target.textContent;
        if (value === 'C') {
            clearDisplay();
        } else if (value === '=') {
            calculate();
        } else if (operators.includes(value)) {
            handleOperator(value);
        } else {
            handleNumber(value);
        }
    });
});

function clearDisplay() {
    display.value = '';
}

function handleNumber(value) {
    if (display.value === '0') {
        display.value = value;
    } else {
        display.value += value;
    }
}

function handleOperator(value) {
    if (display.value !== '') {
        calculate();
    }
    display.value += value;
}

function calculate() {
    const expression = display.value;
    let result = 0;
    let operatorIndex = 0;
    let number = '';

    for (let i = 0; i < expression.length; i++) {
        if (operators.includes(expression[i])) {
            operatorIndex = i;
            number = expression.slice(0, i);
            break;
        }
    }

    if (operatorIndex > 0) {
        number = parseFloat(number);
        const operator = expression[operatorIndex];
        const secondNumber = expression.slice(operatorIndex + 1);

        switch (operator) {
            case '+':
                result = number + parseFloat(secondNumber);
                break;
            case '-':
                result = number - parseFloat(secondNumber);
                break;
            case '\*':
                result = number * parseFloat(secondNumber);
                break;
            case '/':
                result = number / parseFloat(secondNumber);
                break;
        }
    }

    display.value = result.toString();
}

// Add event listener for decimal button
document.getElementById('decimal').addEventListener('click', (e) => {
    const value = e.target.textContent;
    if (display.value.includes('.')) {
        return;
    }
    handleNumber(value);
});

Explanation of the JavaScript Code

  1. Getting Elements: We get references to the display and buttons using document.getElementById and document.querySelectorAll.

  2. Event Listeners: We add event listeners to each button to handle different actions.

  3. Clear Display: The clearDisplay function clears the display by setting its value to an empty string.

  4. Handle Number: The handleNumber function appends the number to the display if the display is not already set to '0'.

  5. Handle Operator: The handleOperator function checks if the display is not empty before adding the operator to the display.

  6. Calculate: The calculate function performs the calculation based on the operator and the numbers entered.

  7. Decimal Button: We add an event listener for the decimal button to ensure that only one decimal point is added to the display.

Testing the Calculator

To test the calculator, open the HTML file in a browser and click on the buttons to perform calculations. The display should update accordingly.

Conclusion

In this blog post, we have covered the basics of creating a calculator using JavaScript. We have discussed the functionality of a calculator, the HTML structure, and the JavaScript code required to make it functional. With this guide, you can create a basic calculator that can perform simple arithmetic operations. This calculator can be further enhanced by adding more features and improving the user interface.

Future Enhancements

  1. Add More Operators: You can add more mathematical operators like square root, exponentiation, and trigonometric functions.

  2. Improve User Interface: Enhance the appearance of the calculator by adding more styles and animations.

  3. Handle Errors: Implement error handling to prevent invalid inputs and ensure the calculator remains functional.

  4. Add Scientific Functions: Include scientific functions like logarithms, trigonometric functions, and more.

By following these steps and enhancing the calculator as needed, you can create a robust and user-friendly calculator that can be used for various purposes.