Coding A Simple Calculator With JavaScript

Coding A Simple Calculator With JavaScript

Any programming language requires a lot of work and determination to master, and by developing this calculator, you can improve your coding abilities.

Webp.net-resizeimage.jpg Mastering any programming language takes patience and lots of practice. You can only get better at coding by coding. One way you can polish your programming skills is to build projects. Building programs like calculators, to-do lists, or quizzes are a great way to develop your coding abilities.

You will master how to create a simple calculator with pure JavaScript in this article. To build this project, you will need basic knowledge of JavaScript and HTML. This tutorial is beginner-friendly and easy to follow.

Logic Of This Calculator

  • This calculator will perform basic arithmetic operations like; addition, subtraction, multiplication, and division.
  • It will accept and respond to user input.
  • It will return an error message if the user enters invalid input.
  • It will return numbers inputted by the user as floats to prevent errors when inputting a decimal number.
  • It will ask the user if they wish to perform another operation.

Building The Calculator

To provide us with an interface to work with, you should first generate an index.html file and a script.js file in your code editor. After creating your files, using the script tag, link your script.js file to your HTML file.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Calculator</title>
  <script src="script.js"></script>
</head>
<body>

</body>
</html>

Step 1: Declare A Constant Variable

Declare a variable, call it simpleCalculator, and assign it a Boolean value. In JavaScript, we use the; let, const, or var keywords to declare variables.

We assigned it a Boolean value so that we have a condition for when the loop runs. Although you can give this variable any value, you should remember to repeat that requirement at the start of your loop.

Reminder: All JavaScript code must end in a semi-colon.

let simpleCalculator = true;

Step 2: Begin Your Loop

Open your while loop. We will be enclosing a few if/else statements in our while loop to state the conditions to be met.

We use loops when there are actions that we want to implement repeatedly. Although you do not have to use a while loop, as other loops should work fine, this tutorial will use a while loop.

while (simpleCalculator = true) {

Step 3: Accepting User Input

Declare another variable inside your while loop and call it operations. Operations will receive input from the user using the window.prompt() function. It will allow the user to specify which arithmetic operation they want to perform.

We will only ask the user for two numbers to reduce technicalities in this calculator. Again, using the let keyword, we will declare two variables asking the user for the two numbers with which we would perform the arithmetic operations.

    let operations = window.prompt("Select an operation to perform: Type '1' for Addition '2' for Subtraction '3' for Multiplication '4' for Division");

    let num1 = window.prompt('Enter a number :');
    let num2 = window.prompt('Enter another number :');

Tip: JavaScript reads code from top to bottom. If it meets an error at the top, it will read the preceding code as an error.

STEP 4: Using If/Else Statements

Begin your if/else statements. Here we will tell our code what to do when the user inputs specific values.

  • We want to specify what happens when the user inputs “1”, “2,” “3,” or “4”.
  • We also want to specify what would happen if the user’s input is invalid.

CONDITIONS

  1. If the user inputs “1”, “2”, “3”, or “4”, the code should perform addition, subtraction, multiplication, or division, respectively. We will return each number as a float to avoid errors if the user inputs decimals.

  2. We must now declare what will happen if the user enters invalid input. Using alert(), we will output an error message.

    if (operations == "1") {
    
        let sum = parseFloat(num1) + parseFloat(num2);
        alert('The sum is ' + sum);
     }
    
     else if (operations == "2") {
    
        let difference = parseFloat(num1) - parseFloat(num2);
        alert('The difference is ' + difference);
    }
    
     else if (operations == "3") {
    
        let product = parseFloat(num1) * parseFloat(num2);
        alert('The product is ' + product);
     }
    
      else if (operations == "4") {
    
       let quotient = parseFloat(num1) / parseFloat(num2)
        alert('The quotient is ' + quotient); 
      }
     else {
         alert("Invalid input. Stop");
     }
    

Step 5: Another Operation? Yes or No?

Finally, we will ask our users if they want to perform another operation. To do this, we will declare a variable and output a prompt. We will also address what should happen when Yes or No is picked using two if statements.

Note: We use arrays to connote the options available to the user.

Tip: Break statements are used to stop a loop or stop more lines of code from executing. For the first, if statement, we tell our code to restart the loop when yes is the user’s choice. For the last statement, we introduce break so our while loop stops running when the user picks “No.”

let reRun = window.prompt("Would you like to perform another operation? " + ["Yes", "No"]);
    if (reRun == "Yes") {

    }
    if (reRun == "No") {
        break;
    }
}

We have successfully built a simple calculator using just JavaScript.

Why Should You Build More Projects?

Getting better at JavaScript requires knowing more than just JavaScript syntax—you have to understand the logic of solving problems. Building more projects like this will sharpen your ability to think like a developer and find solutions to problems.

Here is a link to the GitHub repository of this project.