Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to make a calculator in JavaScript

Introduction

Building a calculator is a great project for someone who's learning programming, especially when working with JavaScript. It helps you understand how to handle user input, perform calculations, and display the result on the screen. In this tutorial, we will create a simple calculator using JavaScript, HTML, and CSS.

Don't worry if you're not familiar with some terms or concepts mentioned in this tutorial. We'll explain everything along the way, and by the end, you'll have a working calculator that you can customize and improve.

Setting up the HTML

First, we need to set up the HTML structure for our calculator. We'll create a container for the calculator, which will hold all of its elements, such as input fields and buttons.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>JavaScript Calculator</title>
</head>
<body>
  <div id="calculator">
    <!-- Calculator elements will go here -->
  </div>
</body>
</html>

Now, let's add the elements we'll need for our calculator. We'll need an input field to display the current value (think of it as a calculator screen), and buttons for digits 0-9, decimal point, and basic arithmetic operations (+, -, *, /). We'll also add a button for clearing the input field, and one for calculating the result.

<div id="calculator">
  <input type="text" id="display" readonly>
  <div id="buttons">
    <button>1</button>
    <button>2</button>
    <button>3</button>
    <button>+</button>
    <button>4</button>
    <button>5</button>
    <button>6</button>
    <button>-</button>
    <button>7</button>
    <button>8</button>
    <button>9</button>
    <button>*</button>
    <button>.</button>
    <button>0</button>
    <button>/</button>
    <button>C</button>
    <button>=</button>
  </div>
</div>

Styling the calculator with CSS

Next, let's add some basic styling to our calculator using CSS. We'll give the calculator container a fixed width and center it on the screen. The input field (calculator screen) will have a larger font-size and a light gray background. The buttons will have a fixed width and height, and we'll arrange them in a grid layout.

<style>
  body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
    background-color: #f0f0f0;
  }

  #calculator {
    width: 200px;
    background-color: #ffffff;
    padding: 20px;
    border-radius: 5px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  }

  #display {
    width: 100%;
    height: 40px;
    margin-bottom: 10px;
    text-align: right;
    background-color: #f0f0f0;
    border: 1px solid #cccccc;
    border-radius: 4px;
    font-size: 18px;
    outline: none;
  }

  #buttons {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 5px;
  }

  button {
    width: 100%;
    height: 40px;
    font-size: 18px;
    background-color: #d1d1d1;
    border: none;
    border-radius: 4px;
    cursor: pointer;
  }

  button:hover {
    background-color: #bcbcbc;
  }
</style>

Adding functionality with JavaScript

Now that we have the structure and styling for our calculator, let's add functionality using JavaScript. First, we'll create a function called appendToDisplay that will update the input field (calculator screen) with the clicked button's value.

function appendToDisplay(value) {
  const display = document.getElementById('display');
  display.value += value;
}

Next, we'll create a function called clearDisplay, which will clear the input field when the "C" button is clicked.

function clearDisplay() {
  const display = document.getElementById('display');
  display.value = '';
}

Now, we need to create a function called calculate that will take the current value in the input field (calculator screen) and perform the desired calculation.

function calculate() {
  const display = document.getElementById('display');
  try {
    display.value = eval(display.value);
  } catch (error) {
    display.value = 'Error';
  }
}

The eval() function in JavaScript allows us to evaluate a string of code, which in our case, will be a mathematical expression. However, using eval() can be dangerous, as it could potentially execute malicious code. In this tutorial, we'll use it for simplicity, but in a real-world application, it's recommended to use a safer alternative, like a math library or writing your own calculation functions.

Finally, we need to add event listeners to our buttons, so that when they are clicked, the appropriate function is called.

const buttons = document.querySelectorAll('button');

buttons.forEach((button) => {
  button.addEventListener('click', () => {
    if (button.textContent === 'C') {
      clearDisplay();
    } else if (button.textContent === '=') {
      calculate();
    } else {
      appendToDisplay(button.textContent);
    }
  });
});

Now, you should have a working calculator that can perform basic arithmetic operations. You can further customize the styling and functionality of your calculator, or even add more advanced features like parentheses, exponents, or trigonometric functions.

Conclusion

In this tutorial, we've built a simple calculator using JavaScript, HTML, and CSS. We've learned how to handle user input, perform calculations, and display the result on the screen. Building a calculator is an excellent project for learning programming, as it helps you understand the basics of user interactions and mathematical operations. You can now experiment with your calculator, adding more features, or improving its design and functionality. Happy coding!