JavaScript Program to Make a Simple Calculator

Updated on November 15, 2024
Make a simple calculator header image

Introduction

A calculator program in JavaScript provides an excellent way to understand the fundamental concepts of programming like handling user input, executing arithmetic operations, and displaying results. Creating a simple calculator involves defining variables, reading user inputs, applying arithmetic formulas, and updating the webpage dynamically.

In this article, you will learn how to construct a basic calculator using JavaScript. Explore various examples, starting with basic arithmetic operations and progressing to the integration of these operations into a simple HTML interface.

Creating Basic Operations

Perform Addition

  1. Define two numbers to add.

  2. Sum the numbers using the + operator.

  3. Display the result in the console.

    javascript
    const num1 = 5;
    const num2 = 3;
    const sum = num1 + num2;
    console.log('Sum:', sum);
    

    This code sums num1 and num2, then prints the result "Sum: 8" to the console.

Perform Subtraction

  1. Define two numbers.

  2. Subtract the second number from the first.

  3. Display the result in the console.

    javascript
    const num1 = 10;
    const num2 = 6;
    const difference = num1 - num2;
    console.log('Difference:', difference);
    

    This snippet subtracts num2 from num1 and logs "Difference: 4" to the console.

Perform Multiplication

  1. Specify two numbers.

  2. Multiply them using the * operator.

  3. Print the output.

    javascript
    const num1 = 4;
    const num2 = 7;
    const product = num1 * num2;
    console.log('Product:', product);
    

    The code calculates the product of num1 and num2, resulting in "Product: 28".

Perform Division

  1. Assign values to two variables.

  2. Divide the first number by the second.

  3. Log the result to the console.

    javascript
    const num1 = 20;
    const num2 = 5;
    const quotient = num1 / num2;
    console.log('Quotient:', quotient);
    

    This division operation yields a quotient of 4, as displayed in the console log.

Integrating Operations into a Web Interface

HTML Structure

  • Create a simple HTML form with input fields for the numbers and dropdown for selecting an operation.

  • Add a button to perform the calculation.

    html
    <form>
        <input type="text" id="num1" placeholder="Enter First Number">
        <input type="text" id="num2" placeholder="Enter Second Number">
        <select id="operation">
            <option value="add">Add</option>
            <option value="subtract">Subtract</option>
            <option value="multiply">Multiply</option>
            <option value="divide">Divide</option>
        </select>
        <button type="button" onclick="performCalculation()">Calculate</button>
    </form>
    <div id="result"></div>
    

JavaScript Implementation

  • Implement a function to fetch user inputs, perform the selected operation, and display the result.

    javascript
    function performCalculation() {
        const num1 = parseFloat(document.getElementById('num1').value);
        const num2 = parseFloat(document.getElementById('num2').value);
        const operation = document.getElementById('operation').value;
        let result;
    
        switch(operation) {
            case 'add':
                result = num1 + num2;
                break;
            case 'subtract':
                result = num1 - num2;
                break;
            case 'multiply':
                result = num1 * num2;
                break;
            case 'divide':
                result = num1 / num2;
                break;
            default:
                result = 'Invalid operation';
        }
    
        document.getElementById('result').innerText = 'Result: ' + result;
    }
    

    This script enables the calculator to process user input from the web form, calculate based on the chosen arithmetic operation, and display the result on the same page.

Conclusion

By creating a JavaScript program for a simple calculator, you gain a foundational understanding of handling user input, performing arithmetic operations, and dynamically updating web content. Start with basic arithmetic in standalone scripts and gradually integrate these into a functional web-based application. With this knowledge, modifying or expanding the calculator’s functionality becomes much more accessible, offering a solid starting point for more complex programming tasks.