๐Ÿงฎ๐Ÿ’ป Crunch the Numbers: Building a JavaScript Calculator Step-by-Step ๐Ÿš€ย for Beginners

ยท

5 min read

Building a JavaScript Calculator: Step-by-Step Tutorial with Code

Are you interested in building your own calculator using JavaScript? Then you are in the right place! In this article, we will guide you through the step-by-step process of building a JavaScript calculator with code. You will learn how to create a functional calculator that performs basic mathematical operations such as addition, subtraction, multiplication, and division.

Setting up the HTML file

The first step in building our calculator is to set up the HTML file. Open your text editor and create a new HTML file. Add a container div element with a class of "calculator" and a screen div element inside it with a class of "screen". This is where we will display the calculations and the results.

<div class="calculator">
  <div class="screen"></div>
</div>

Next, add buttons for each of the mathematical operations you want to include in your calculator. We will use HTML buttons with unique IDs for each button, which will make it easy for us to reference them in the JavaScript code. Here is an example of how to add the addition and subtraction buttons:

<button id="add">+</button>
<button id="subtract">-</button>

Creating the calculator layout using CSS

After setting up the HTML file, the next step is to style the calculator using CSS. Add the following CSS code to create a grid layout for the calculator:

.calculator {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: repeat(5, 1fr);
  gap: 5px;
  width: 300px;
  height: 400px;
  background-color: #fff;
  border-radius: 10px;
  padding: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}

This will create a grid layout with 4 columns and 5 rows, with a gap of 5px between each button. Next, add styles to the buttons to create a clean and organized look:

button {
  border: none;
  outline: none;
  background-color: #eee;
  font-size: 24px;
  cursor: pointer;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
  border-radius: 5px;
  padding: 10px;
}

Finally, add hover and click effects to the buttons to enhance user experience:

button:hover {
  background-color: #ccc;
}

button:active {
  box-shadow: none;
}

Adding JavaScript to perform calculations

The most critical part of building a calculator is adding JavaScript to perform the calculations. Create a new JavaScript file and link it to your HTML file using the script tag. Here's how to create a function for addition:

function add(num1, num2) {
  return num1 + num2;
}

This function takes two parameters, num1 and num2, and returns their sum. We will use similar functions for subtraction, multiplication, and division.

Next, add an event listener to the addition button that calls the add function and displays the result on the screen:

const addBtn = document.querySelector("#add");
addBtn.addEventListener("click", function() {
  const num1 = parseFloat(document.querySelector(".screen").textContent);
  const num2 = parseFloat(prompt("Enter second number:"));
  const result = add(num1, num2);
  document.querySelector(".screen").textContent = result;
});

This code gets the first number from the screen div element and prompts the user for the second number. It then calls the add function with the two numbers as arguments and stores the result in a variable called "result". Finally, it displays the result on the screen by setting the textContent of the screen div element to the value of "result".

You can follow a similar process for the subtraction, multiplication, and division buttons. Here's how to create the function for subtraction:

function subtract(num1, num2) {
  return num1 - num2;
}

And here's how to add an event listener to the subtraction button:

const subtractBtn = document.querySelector("#subtract");
subtractBtn.addEventListener("click", function() {
  const num1 = parseFloat(document.querySelector(".screen").textContent);
  const num2 = parseFloat(prompt("Enter second number:"));
  const result = subtract(num1, num2);
  document.querySelector(".screen").textContent = result;
});

You can repeat this process for the multiplication and division buttons, using the appropriate functions and event listeners.

Handling Errors

While building a calculator, it's essential to handle errors that may occur when the user inputs invalid values or performs unsupported operations. Here's how to add an error message when the user inputs an invalid value:

const num1 = parseFloat(document.querySelector(".screen").textContent);
if (isNaN(num1)) {
  document.querySelector(".screen").textContent = "Error";
}

This code checks if the value of num1 is not a number using the isNaN() function. If it's not a number, it displays an error message on the screen by setting the textContent of the screen div element to "Error".

You can also add error handling for unsupported operations such as dividing by zero:

function divide(num1, num2) {
  if (num2 === 0) {
    return "Error";
  }
  return num1 / num2;
}

This code checks if the value of num2 is zero and returns an error message if it is. Otherwise, it performs the division operation and returns the result.

Conclusion

In conclusion, building a JavaScript calculator requires a step-by-step process of setting up the HTML file, creating the calculator layout using CSS, and adding JavaScript to perform calculations. With this guide, you can create a functional calculator that performs basic mathematical operations. Remember to handle errors that may occur, such as invalid input values and unsupported operations.

FAQs

  1. Can I customize the design of my JavaScript calculator?

    Yes, you can customize the design of your calculator by modifying the CSS code.

  2. Can I add more mathematical operations to my calculator?

    Yes, you can add more mathematical operations such as square root, percentage, and exponentiation.

  3. Is it possible to add a history feature to my calculator?

    Yes, you can add a history feature that displays the previous calculations and results.

  4. How can I make my calculator responsive?

    You can use CSS media queries to make your calculator responsive to different screen sizes.

  5. Do I need to have prior knowledge of JavaScript to build a calculator?

    While prior knowledge of JavaScript is not required, it's helpful to have a basic understanding of variables, functions, and event listeners.

Did you find this article valuable?

Support Learn!Things by becoming a sponsor. Any amount is appreciated!

ย