JavaScript: Implement a Basic Calculator

1. Introduction

A basic calculator is an essential tool that performs arithmetic operations like addition, subtraction, multiplication, and division. In this post, we will design a simple calculator in JavaScript that can handle these four operations.

2. Program Overview

Our guide will involve:

1. Defining a function for each of the arithmetic operations.

2. Creating a main function called a calculator to handle user input and operation selection.

3. Testing our calculator function with some sample inputs.

3. Code Program

// Function for Addition
function add(num1, num2) {
    return num1 + num2;

// Function for Subtraction
function subtract(num1, num2) {
    return num1 - num2;

// Function for Multiplication
function multiply(num1, num2) {
    return num1 * num2;

// Function for Division
function divide(num1, num2) {
    if (num2 === 0) {
        return "Error: Division by zero";
    return num1 / num2;

// Main Calculator Function
function calculator(operation, num1, num2) {
    switch(operation) {
        case "add":
            return add(num1, num2);
        case "subtract":
            return subtract(num1, num2);
        case "multiply":
            return multiply(num1, num2);
        case "divide":
            return divide(num1, num2);
            return "Invalid Operation";

// Sample Test
let operation = "add";  // Change this to "subtract", "multiply", or "divide" for other operations
let number1 = 5;
let number2 = 3;

let result = calculator(operation, number1, number2);
console.log(The result of ${operation} ${number1} and ${number2} is: ${result});


The result of add 5 and 3 is: 8

4. Step By Step Explanation

1. Defining Arithmetic Functions: We start by defining four functions, one for each arithmetic operation. Each function takes two numbers as arguments and returns the result of the respective operation.

2. Handling Division by Zero: In the divide function, we check if the second number (num2) is zero. Division by zero is mathematically undefined, so we return an error message in such a case.

3. Main Calculator Function: The calculator function serves as the main driver of our program. It uses a switch statement to determine which arithmetic function to call based on the chosen operation. If the operation is not recognized, it returns an "Invalid Operation" message.

4. Testing the Calculator: We define a sample operation and two numbers. We then pass these to the calculator function and display the result using a template literal. You can change the operation and numbers to test other scenarios.