• Articles
  • Tutorials
  • Interview Questions
  • Webinars

Calculator Using JavaScript Tutorial: Using JavaScript Basics

Calculator Using JavaScript Tutorial: Using JavaScript Basics

As we go along, you’ll be coding and creating your very own calculator. By the end of this blog, not only will you have a calculator that you’ve made all by yourself, but you’ll also understand more about how JavaScript works. This means you can start making things like games or websites. So, let’s understand the concepts.

Also, make sure to check out the Python vs. JavaScript video on our YouTube channel:

Video Thumbnail

Basic Topics You Should Know to Build Calculator Using JavaScript

Before we start coding our calculator using JavaScript, it’s important to have an understanding of the fundamental concepts that you should know to build a calculator using JavaScript:

Concepts You Should Know
HTML & CSS BasicsUnderstanding the structure of HTML and the styling of CSS is important, as they form the skeleton and skin of your calculator. This includes knowing how to create elements in HTML and style them using CSS.
JavaScript SyntaxFamiliarity with JavaScript syntax is key. This includes understanding variables, functions, event handling, and manipulation of Document Object Model (DOM).
Event ListenersThese are necessary to respond to user actions, such as clicks on calculator buttons. Event listeners in JavaScript allow your application to interact dynamically with user inputs.
Conditional StatementsConditional statements are used to perform different actions based on different conditions. They help in making decisions based on user input, which is essential for the logic of a calculator.
Basic Math OperationsKnowledge of basic math operations like addition, subtraction, multiplication, and division in JavaScript is important. These operations form the core functionality of any basic calculator.

Interested in learning Java? Enroll in our Java Training now!

Basic Calculator Using JavaScript

A basic calculator performs operations like addition, subtraction, multiplication, and division. We’ll go through each step, from setting up the HTML structure to writing the JavaScript code.

Step 1: Setting Up the HTML Structure

Start by creating an HTML file and setting up a basic structure. Include a display area for the calculator and buttons for digits and operations.

<!DOCTYPE html>
<html>
<head>
    <title>Basic Calculator</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <div id="calculator">
        <input type="text" id="display" disabled>
        <div class="button-grid">
            <button class="digit">1</button>
            <button class="digit">2</button>
            <button class="digit">3</button>
            <button class="operator">+</button>
            <button class="digit">4</button>
            <button class="digit">5</button>
            <button class="digit">6</button>
            <button class="operator">-</button>
            <button class="digit">7</button>
            <button class="digit">8</button>
            <button class="digit">9</button>
            <button class="operator">*</button>
            <button class="digit">0</button>
            <button id="clear">C</button>
            <button id="equals">=</button>
            <button class="operator">/</button>
        </div>
    </div>
    <script src="script.js"></script>
</body>
</html>

Get 100% Hike!

Master Most in Demand Skills Now!

Step 2: Styling with CSS

Add some basic styles to make your calculator look more appealing. Create a CSS file and link it to your HTML.

#calculator {
    width: 250px; /* Adjust the width as needed */
    margin: auto;
    border: 1px solid #000; /* Optional: adds a border around the calculator */
    padding: 10px;
    box-sizing: border-box;
}
#display {
    width: 100%;
    height: 40px;
    margin-bottom: 10px;
    text-align: right; /* Aligns text to the right */
    padding: 5px;
    box-sizing: border-box;
}
button {
    width: 46px; /* Adjust button width */
    height: 46px; /* Adjust button height */
    margin: 2px;
    font-size: 16px; /* Adjust font size as needed */
}
/* Grid layout for buttons */
#calculator div {
    display: grid;
    grid-template-columns: repeat(4, 1fr); /* 4 columns */
    grid-gap: 2px;
}

Step 3: Adding JavaScript Functionality

Now, let’s add the functionality using JavaScript. Create a script.js file and start by selecting elements and setting up event listeners.

// Wait for the DOM to be fully loaded
document.addEventListener('DOMContentLoaded', function () {
    // Get the display element and buttons
    const display = document.getElementById('display');
    const digits = document.querySelectorAll('.digit');
    const operators = document.querySelectorAll('.operator');
    // Variables to store the operands and the current operation
    let currentOperation = null;
    let firstOperand = '';
    let secondOperand = '';
    // Add click event listeners to each digit button
    digits.forEach(digit => {
        digit.addEventListener('click', function () {
            // Depending on whether an operation is selected, update the appropriate operand
            if (currentOperation === null) {
                firstOperand += this.innerText;
                display.value = firstOperand;
            } else {
                secondOperand += this.innerText;
                display.value = secondOperand;
            }
        });
    });
    // Add click event listeners to each operator button
    operators.forEach(operator => {
        operator.addEventListener('click', function () {
            // If an operation is already in progress, calculate the result first
            if (currentOperation !== null) {
                calculate();
            }
            // Set the current operation
            currentOperation = this.innerText;
        });
    });
    // Equals button functionality
    document.getElementById('equals').addEventListener('click', function () {
        calculate();
        // Reset the current operation
        currentOperation = null;
    });
    // Clear button functionality
    document.getElementById('clear').addEventListener('click', function () {
        // Reset all values and clear the display
        firstOperand = '';
        secondOperand = '';
        currentOperation = null;
        display.value = '';
    });
    // Function to perform the calculation
    function calculate() {
        // Convert operand strings to numbers
        firstOperand = parseFloat(firstOperand);
        secondOperand = parseFloat(secondOperand);
        // If operands are not numbers, exit the function
        if (isNaN(firstOperand) || isNaN(secondOperand)) return;
        // Perform the calculation based on the operation
        let result;
        switch (currentOperation) {
            case '+':
                result = firstOperand + secondOperand;
                break;
            case '-':
                result = firstOperand - secondOperand;
                break;
            case '*':
                result = firstOperand * secondOperand;
                break;
            case '/':
                result = firstOperand / secondOperand;
                break;
            default:
                return;
        }
        // Display the result and prepare for the next operation
        display.value = result;
        firstOperand = result;
        secondOperand = '';
    }
});

Output

When the above program is executed on any browser, it shows the below output.

Basic Calculator Using JavaScript

Read the Web Development Tutorial to enhance your knowledge!

Scientific Calculator Using JavaScript

Let’s break down the concept of creating a scientific calculator using JavaScript into simpler terms, perfect for beginners. This project is a fantastic way to get hands-on experience with HTML, CSS, and JavaScript, the three core technologies of web development. 

A scientific calculator is like a regular calculator but with superpowers. It can do all the basic stuff like adding or subtracting numbers, and it can also handle more complex math like trigonometry (sine, cosine, etc.), which is handy in many fields like engineering or physics.

Step 1: Setting Up the HTML Structure

<!DOCTYPE html>
<html>
<head>
    <title>Scientific Calculator</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <div id="calculator">
        <input type="text" id="display" disabled>
        <div class="button-grid">
            <!-- Digit buttons -->
            <button class="digit">1</button>
            <button class="digit">2</button>
            <button class="digit">3</button>
            <button class="digit">4</button>
            <button class="digit">5</button>
            <button class="digit">6</button>
            <button class="digit">7</button>
            <button class="digit">8</button>
            <button class="digit">9</button>
            <button class="digit">0</button>
            <!-- Operator buttons -->
            <button class="operator">+</button>
            <button class="operator">-</button>
            <button class="operator">*</button>
            <button class="operator">/</button>
            <!-- Scientific function buttons -->
            <button class="function" data-func="sin">sin</button>
            <button class="function" data-func="cos">cos</button>
            <button class="function" data-func="tan">tan</button>
            <button class="function" data-func="log">log</button>
            <button class="function" data-func="sqrt">√</button>
            <button class="function" data-func="pow">x^y</button>
            <!-- Other buttons -->
            <button id="clear">C</button>
            <button id="equals">=</button>
        </div>
    </div>
    <script src="script.js"></script>
</body>
</html>

Step 2: Styling with CSS

body {
    font-family: 'Arial', sans-serif;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #f4f4f4;
}
#calculator {
    width: 250px;
    background-color: #fff;
    border: 1px solid #ddd;
    border-radius: 10px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
    padding: 20px;
    box-sizing: border-box;
}
#display {
    width: 100%;
    height: 50px;
    border: 1px solid #ddd;
    border-radius: 5px;
    margin-bottom: 20px;
    text-align: right;
    padding: 10px;
    font-size: 18px;
    box-sizing: border-box;
    background-color: #f9f9f9;
}
button {
    width: 46px;
    height: 46px;
    margin: 5px;
    border: none;
    border-radius: 5px;
    font-size: 16px;
    color: #fff;
    background-color: #007bff;
    cursor: pointer;
    transition: background-color 0.3s;
}
button:hover {
    background-color: #0056b3;
}
button.operator {
    background-color: #28a745;
}
button.operator:hover {
    background-color: #1e7e34;
}
button.function {
    background-color: #17a2b8;
}
button.function:hover {
    background-color: #117a8b;
}
button#clear {
    background-color: #dc3545;
}
button#clear:hover {
    background-color: #bd2130;
}
/* Grid layout for buttons */
.button-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    grid-gap: 10px;
}

Check out our JavaScript interview questions to crack high-paying, top-level MNC interviews.

Step 3: Adding JavaScript Functionality

Now, let’s add the functionality using JavaScript. Create a script.js file and start by selecting elements and setting up event listeners.

document.addEventListener('DOMContentLoaded', function () {
    // Selecting elements from the DOM
    const display = document.getElementById('display');
    const digits = document.querySelectorAll('.digit');
    const operators = document.querySelectorAll('.operator');
    const functions = document.querySelectorAll('.function');
    // Variables to store the current state of the calculator
    let currentOperation = null;
    let firstOperand = '';
    let secondOperand = '';
    let awaitingSecondOperand = false;
    // Adding event listeners to digit buttons
    digits.forEach(digit => {
        digit.addEventListener('click', function () {
            if (awaitingSecondOperand) {
                secondOperand = this.innerText;
                display.value = secondOperand;
                awaitingSecondOperand = false;
            } else {
                firstOperand += this.innerText;
                display.value = firstOperand;
            }
        });
    });
    // Adding event listeners to operator buttons
    operators.forEach(operator => {
        operator.addEventListener('click', function () {
            if (!awaitingSecondOperand) {
                currentOperation = this.innerText;
                awaitingSecondOperand = true;
            } else {
                calculate();
                currentOperation = this.innerText;
            }
        });
    });
    // Adding event listeners to scientific function buttons
    functions.forEach(func => {
        func.addEventListener('click', function () {
            applyFunction(this.getAttribute('data-func'));
        });
    });
    // Equals button functionality
    document.getElementById('equals').addEventListener('click', calculate);
    // Clear button functionality
    document.getElementById('clear').addEventListener('click', clearCalculator);
    // Function to perform basic arithmetic calculations
    function calculate() {
        if (currentOperation && !awaitingSecondOperand) {
            firstOperand = parseFloat(firstOperand);
            secondOperand = parseFloat(secondOperand);
            switch (currentOperation) {
                case '+':
                    firstOperand += secondOperand;
                    break;
                case '-':
                    firstOperand -= secondOperand;
                    break;
                case '*':
                    firstOperand *= secondOperand;
                    break;
                case '/':
                    firstOperand /= secondOperand;
                    break;
            }
            display.value = firstOperand;
            secondOperand = '';
            awaitingSecondOperand = true;
        }
    }
    // Function to apply scientific functions
    function applyFunction(func) {
        let value = parseFloat(display.value);
        if (isNaN(value)) return;
        switch (func) {
            case 'sin':
                display.value = Math.sin(value);
                break;
            case 'cos':
                display.value = Math.cos(value);
                break;
            case 'tan':
                display.value = Math.tan(value);
                break;
            case 'log':
                display.value = Math.log(value);
                break;
            case 'sqrt':
                display.value = Math.sqrt(value);
                break;
            case 'pow':
                // For exponentiation, you can implement a method to get the second value (exponent)
                break;
        }
    }
    // Function to clear the calculator's display and reset its state
    function clearCalculator() {
        firstOperand = '';
        secondOperand = '';
        currentOperation = null;
        awaitingSecondOperand = false;
        display.value = '';
    }
});

Output

Scientific Calculator Using JavaScript

Conclusion

As we reach the end of our blog on building a calculator using JavaScript, it’s clear that this project is not just about creating a functional tool but also about deepening our understanding of web development. We started with the basics, setting up our calculator’s look with HTML and CSS, and then we dived into JavaScript to make it work. From adding, subtracting, and multiplying to dividing, we covered all the basic operations. Then, we took it a step further by turning our simple calculator into a scientific one that can do even cooler math stuff like trigonometry. This project isn’t just about building a calculator; it’s a fun and practical way to learn web development. Whether you are just starting out or refreshing your skills, making a calculator is a great way to practice coding and see the immediate results of your hard work.

About the Author

Principal Data Scientist

Meet Akash, a Principal Data Scientist who worked as a Supply Chain professional with expertise in demand planning, inventory management, and network optimization. With a master’s degree from IIT Kanpur, his areas of interest include machine learning and operations research.