How to Make a Calculator in JavaScript from Scratch


Are you intrigued by the world of coding and eager to build something fun? We’re about to take a delightful dive into creating one of the simplest yet most useful applications: a calculator! In this blog, you’ll discover how to make a calculator in JavaScript, all while learning some essential programming concepts. Don’t worry if you’re a newbie—I’ll guide you step-by-step with plain and simple instructions. By the end of this journey, you’ll have created a basic calculator that performs arithmetic operations, and you’ll be more confident in your coding skills. Excited to get started? Let’s jump right in!

HTML and JavaScript Code for a Simple Calculator

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple Calculator</title>
    <style>
        body { font-family: Arial, sans-serif; }
        .calculator { width: 200px; margin: 50px auto; }
        input, button { width: 40px; height: 40px; margin: 5px; font-size: 20px; }
        .row { display: flex; justify-content: space-between; }
        .result { margin-top: 10px; font-size: 20px; }
    </style>
</head>
<body>

<div class="calculator">
    <input type="text" id="number1" placeholder="Enter number">
    <input type="text" id="number2" placeholder="Enter number">
    <div class="row">
        <button onclick="add()">Add</button>
        <button onclick="subtract()">Subtract</button>
    </div>
    <div class="row">
        <button onclick="multiply()">Multiply</button>
        <button onclick="divide()">Divide</button>
    </div>
    <div id="result" class="result">Result: </div>
</div>

<script>
    function add() {
        const num1 = parseFloat(document.getElementById('number1').value);
        const num2 = parseFloat(document.getElementById('number2').value);
        const result = num1 + num2;
        document.getElementById('result').innerText = 'Result: ' + result;
    }

    function subtract() {
        const num1 = parseFloat(document.getElementById('number1').value);
        const num2 = parseFloat(document.getElementById('number2').value);
        const result = num1 - num2;
        document.getElementById('result').innerText = 'Result: ' + result;
    }

    function multiply() {
        const num1 = parseFloat(document.getElementById('number1').value);
        const num2 = parseFloat(document.getElementById('number2').value);
        const result = num1 * num2;
        document.getElementById('result').innerText = 'Result: ' + result;
    }

    function divide() {
        const num1 = parseFloat(document.getElementById('number1').value);
        const num2 = parseFloat(document.getElementById('number2').value);
        if (num2 !== 0) {
            const result = num1 / num2;
            document.getElementById('result').innerText = 'Result: ' + result;
        } else {
            document.getElementById('result').innerText = 'Result: Cannot divide by zero';
        }
    }
</script>

</body>
</html>

Explanation of the Code

The code provided is a simple calculator built using HTML and JavaScript. Here’s a step-by-step breakdown:

HTML Structure

  • The code sets up a basic web page with a header titled “Simple Calculator.”
  • It features two inputs for users to enter numbers, along with buttons for each operation: add, subtract, multiply, and divide.

JavaScript Functions

  • The script includes four functions—add, subtract, multiply, and divide.
  • On clicking a button, the respective function runs, taking numbers from the input fields. These numbers undergo conversion to floating-point numbers using parseFloat, which allows for decimal calculations.

Operations and Result Display

  • Based on the operation selected, the script calculates the result.
  • The result appears below the buttons in a section with the ID result.
  • For division, the script checks for zero to avoid dividing by zero.

This straightforward approach makes it easy for beginners to understand how to make a calculator in JavaScript.

Result:

The output of this HTML and JavaScript code will display a simple calculator with two input fields for numbers and buttons for performing basic arithmetic operations (addition, subtraction, multiplication, and division). Here’s how the output will appear:

Webpage Layout:

  • Input Fields: Two text fields will appear labeled “Enter number”, where the user can enter numeric values.
  • Operation Buttons: Four buttons will be displayed below the input fields:
    • Add
    • Subtract
    • Multiply
    • Divide
  • Result Area: A section titled “Result: ” will appear below the buttons, where the calculated result will be shown after each operation.

Example Interactions:

  1. If the user enters 5 in the first input field and 3 in the second input field, and then clicks the “Add” button, the result displayed will be:makefileCopy codeResult: 8
  2. If the user enters 5 and 3, then clicks the “Subtract” button, the result will be:makefileCopy codeResult: 2
  3. If the user enters 5 and 3, then clicks the “Multiply” button, the result will be:makefileCopy codeResult: 15
  4. If the user enters 5 and 0, then clicks the “Divide” button, the result will be:vbnetCopy codeResult: Cannot divide by zero

The calculator allows for simple arithmetic operations and handles the “divide by zero” error gracefully.

Real-Life Uses of Making a Calculator in JavaScript

Let’s take a step back and explore some real-life scenarios where making a calculator in JavaScript becomes incredibly practical and relatable:

  • Personal Finance Management: Crafting a custom calculator allows you to maintain your budget by quickly calculating expenses, splitting bills, or estimating your savings over time!
  • Educational Tools: Building an interactive calculator can provide a hands-on learning tool for students, helping them to understand mathematical concepts better.
  • E-commerce Platforms
    Online shops can integrate calculators to provide users with instant price calculations, discounts, or tax computations, enhancing the shopping experience.
  • Health and Fitness: Use JavaScript calculators to create comprehensive fitness plans by calculating BMI, calorie intake, or workout regimens tailored to your body metrics.
  • Gaming and Puzzles: Got a knack for games? You can build simple puzzle games or strategic calculators to assist in chess or board game strategies.

Top Interview Questions on Building a JavaScript Calculator

Here’s a concise set of interview questions and answers about ‘Make a Calculator in JavaScript’:

  1. What is the primary purpose of using JavaScript to make a calculator?
    JavaScript enables interactive and dynamic web applications, making it ideal for creating a responsive calculator interface.
    Can you list the basic operations a JavaScript calculator should perform?
    A basic JavaScript calculator should handle addition, subtraction, multiplication, division, and possibly exponentiation.
    Why is the ‘eval()’ function often used in building a calculator?
    ‘eval()’ evaluates string expressions, making it useful for executing arithmetic operations entered by users.

  2. How can you implement input validation in a JavaScript calculator?
    Use conditional checks to ensure inputs are numbers and handle cases like division by zero to prevent errors.
    What role does CSS play in a JavaScript calculator?
    CSS styles the calculator, enhancing its appearance and user interface, but doesn’t affect functionality.
Our AI-powered js online compiler lets users instantly write, run, and test code, making learning JavaScript seamless. With AI assistance, coding becomes intuitive and efficient, helping users understand concepts faster while providing a friendly environment for beginners to experiment and grow.

Enhancements to Make Your Calculator Even Better

After building the basic version, you can improve your calculator with some additional features:

  1. Clear Button: Add a button to clear all input fields.
  2. Keyboard Input Support: Allow users to perform calculations using their keyboard.
  3. Complex Calculations: Expand the functionality to handle more complex operations like square roots or exponents.
  4. Styling: Use CSS to create a more visually appealing layout with responsive design.

Conclusion

Building a calculator using JavaScript is a perfect way to strengthen your coding skills. With practice, you can enhance it further. For more learning adventures, check out Newtum. Keep exploring, and don’t hesitate to share your creations with the coding community!

Edited and Compiled by

This blog was compiled and edited by Rasika Deshpande, who has over 4 years of experience in content creation. She’s passionate about helping beginners understand technical topics in a more interactive way.

About The Author