Tutorials

How to Build a Basic Calculator with JavaScript

Spread the love

Building a basic calculator is a great project for beginners looking to get comfortable with JavaScript. It helps you understand key concepts like functions, event handling, and DOM manipulation. Today, we’ll walk through the steps to create a simple calculator that can handle basic arithmetic operations like addition, subtraction, multiplication, and division.

1. Setting Up Your Environment

Before we begin, make sure your development environment is ready:

  • A text editor or IDE: Any code editor will work, but Visual Studio Code is recommended for its features and ease of use.
  • A browser: Since we’ll be using JavaScript, you can test your code directly in your browser.

2. Creating the HTML Structure

Let’s start by setting up the basic HTML structure for our calculator.

  1. Create a new HTML file:

    Open your text editor and create a new file named index.html.

  2. Add the HTML boilerplate:

    Inside index.html, add the following code:

    <!DOCTYPE html>
    <html lang="en">
    <head>
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>Basic Calculator</title>
     <style>
       body {
         display: flex;
         justify-content: center;
         align-items: center;
         height: 100vh;
         font-family: Arial, sans-serif;
         background-color: #f4f4f4;
       }
       .calculator {
         border: 1px solid #ccc;
         padding: 20px;
         border-radius: 10px;
         background-color: white;
       }
       input {
         width: 160px;
         margin-bottom: 10px;
         padding: 10px;
         font-size: 18px;
         text-align: right;
       }
       .buttons {
         display: grid;
         grid-template-columns: repeat(4, 40px);
         grid-gap: 10px;
       }
       button {
         padding: 10px;
         font-size: 18px;
         cursor: pointer;
       }
     </style>
    </head>
    <body>
     <div class="calculator">
       <input type="text" id="display" disabled />
       <div class="buttons">
         <button>7</button>
         <button>8</button>
         <button>9</button>
         <button>/</button>
         <button>4</button>
         <button>5</button>
         <button>6</button>
         <button>*</button>
         <button>1</button>
         <button>2</button>
         <button>3</button>
         <button>-</button>
         <button>0</button>
         <button>.</button>
         <button>=</button>
         <button>+</button>
       </div>
     </div>
     <script src="script.js"></script>
    </body>
    </html>

    This code creates a basic structure for our calculator with an input field to display the numbers and buttons for digits and operations.

3. Adding JavaScript Functionality

Now, let’s make our calculator functional using JavaScript.

  1. Create a new JavaScript file:

    In the same directory as index.html, create a new file named script.js.

  2. Write the JavaScript code:

    Inside script.js, add the following code:

    const display = document.getElementById('display');
    const buttons = document.querySelectorAll('button');
    
    let currentInput = '';
    let operator = '';
    let previousInput = '';
    
    buttons.forEach(button => {
     button.addEventListener('click', () => {
       const value = button.textContent;
    
       if (value === '=') {
         if (currentInput && previousInput && operator) {
           display.value = eval(`${previousInput} ${operator} ${currentInput}`);
           currentInput = display.value;
           previousInput = '';
           operator = '';
         }
       } else if (['+', '-', '*', '/'].includes(value)) {
         if (currentInput) {
           operator = value;
           previousInput = currentInput;
           currentInput = '';
         }
       } else {
         currentInput += value;
         display.value = currentInput;
       }
     });
    });

    This JavaScript code handles the calculator’s logic. It listens for button clicks, updates the display, and performs calculations when the equals button is clicked.

4. Testing the Calculator

Save all your files and open index.html in your browser. You should see a basic calculator interface. Try performing some calculations to ensure everything works correctly.

5. Enhancing the Calculator

To make your calculator more user-friendly, consider adding the following features:

  • Keyboard support: Allow users to interact with the calculator using their keyboard.
  • Clear button: Add a button to clear the current input.
  • Error handling: Implement logic to handle invalid operations (e.g., division by zero).

6. Conclusion: You’ve Built a Basic Calculator!

Congratulations! You’ve successfully built a basic calculator using JavaScript. This project is a great way to reinforce your understanding of JavaScript fundamentals and DOM manipulation. From here, you can continue to build more complex applications, enhancing your skills with every step.

mahtab2003

Passionate about blending the power of AI with human creativity, Mehtab Hassan crafts insightful and engaging articles by leveraging cutting-edge technology and thorough web research. With a keen eye for detail and a commitment to delivering high-quality content, he brings a unique perspective to every piece. Whether exploring the latest trends or diving deep into complex topics, Mehtab Hassan ensures that each article is both informative and accessible, making learning an enjoyable journey for all readers.

Leave a Reply

Your email address will not be published. Required fields are marked *