Tutorial Step-by-Step: Creating a Simple Calculator with JavaScript

Tutorial Step-by-Step: Creating a Simple Calculator with JavaScript

Welcome to the tutorial "Step-by-Step Tutorial: Building a Simple Calculator with JavaScript". In this tutorial, you will learn how to create a basic calculator using the JavaScript programming language. We will cover each step in detail, starting from creating the basic HTML structure, adding styles with CSS, to writing the calculator logic with JavaScript.

The goal of this tutorial is to provide a clear and easy-to-follow guide for creating a simple calculator capable of performing basic arithmetic operations such as addition, subtraction, multiplication, and division. By completing this tutorial, you will gain a better understanding of how JavaScript works and how to use it to build interactive web applications.

Before we begin, make sure you have a basic understanding of HTML, CSS, and JavaScript. If you are not familiar with these, it is recommended to learn them first so you can follow the tutorial more easily and effectively. Let's start our journey in building a simple calculator with JavaScript!

Setting Up the Development Environment

Before diving into creating a simple calculator with JavaScript, it's important to set up a comfortable and efficient development environment. This step includes choosing the right code editor and organizing the project folder structure. Here are some recommendations for code editors and guidelines on how to structure your project folder.

Code Editor

Choosing the right code editor can greatly aid in the development process. Here are some popular code editors widely used by web developers:

  • Visual Studio Code (VS Code): An open-source code editor from Microsoft known for its rich features such as debugging, Git control, and extensibility through plugins.

  • Sublime Text: A lightweight and fast code editor with a clean interface and support for various programming languages.

  • Atom: An open-source code editor developed by GitHub, offering high customization and integration with GitHub.

Choose one of these editors based on your preference. All these editors support syntax highlighting, auto-completion, and many other features that will facilitate writing your JavaScript code.

Folder Structure

To keep your project organized and easily accessible, it's important to structure your folders properly. Here is a suggested folder structure for our calculator project:

my-calculator-project/
│
├── index.html
├── styles.css
└── script.js
  • index.html: The main HTML file that will load the basic structure of our calculator.

  • styles.css: The CSS file used to add styles to the calculator.

  • script.js: The JavaScript file containing the calculator logic.

With an organized folder structure like this, you can easily manage and edit each part of your calculator project. After setting up the development environment, we are ready to move on to the next step, which is creating the HTML structure for the calculator.

Creating HTML Structure

To start building a simple calculator with JavaScript, the first step is to create the HTML structure. HTML will form the foundation of our calculator, where all elements such as display screen and buttons will be placed.

Creating HTML File

The first step is to create a new HTML file. Follow these steps:

  1. Open your preferred code editor (e.g., VS Code, Sublime Text, or Atom).

  2. Create a new file and name it index.html.

  3. Save the file inside your project folder.

Basic HTML Structure

After creating the HTML file, we will add the basic HTML structure for the calculator. This structure includes elements such as a title, display screen, numeric buttons, and operators.

Here is the basic HTML code for a simple calculator:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kalkulator Sederhana</title>
</head>
<body>
    <div class="calculator">
        <input type="text" id="display" disabled>
        <br>
        <input type="button" value="7" onclick="addToDisplay('7')">
        <input type="button" value="8" onclick="addToDisplay('8')">
        <input type="button" value="9" onclick="addToDisplay('9')">
        <input type="button" value="/" onclick="addToDisplay('/')">
        <br>
        <input type="button" value="4" onclick="addToDisplay('4')">
        <input type="button" value="5" onclick="addToDisplay('5')">
        <input type="button" value="6" onclick="addToDisplay('6')">
        <input type="button" value="*" onclick="addToDisplay('*')">
        <br>
        <input type="button" value="1" onclick="addToDisplay('1')">
        <input type="button" value="2" onclick="addToDisplay('2')">
        <input type="button" value="3" onclick="addToDisplay('3')">
        <input type="button" value="-" onclick="addToDisplay('-')">
        <br>
        <input type="button" value="0" onclick="addToDisplay('0')">
        <input type="button" value="." onclick="addToDisplay('.')">
        <input type="button" value="=" onclick="calculate()">
        <input type="button" value="+" onclick="addToDisplay('+')">
        <br>
        <input type="button" value="C" onclick="clearDisplay()">
    </div>
</body>
</html>

Explanation of the code above:

  • DOCTYPE and Basic HTML Element: The first line defines the document as HTML5. The elements <html>, <head>, and <body> form the basic structure of the HTML document.

  • Meta Tag and Title: The charset and viewport meta tags are used for character set and display settings. The <title> element provides the title of the web page.

  • Calculator Container: The <div> element with class "calculator" serves as the main container for the calculator.

  • Display Screen: The <input> element with id "display" is used to display the calculation results.

  • Number and Operator Buttons: Various <input> elements with type "button" are used to create number and operator buttons, each with onclick attribute to handle button clicks.

With this basic HTML structure, we have a framework for a calculator that can be further developed by adding CSS styles and JavaScript logic.

Adding Styles with CSS

In this step, we will add visual styles to the calculator we've created using HTML. Using CSS (Cascading Style Sheets), we can enhance the appearance of the calculator to make it more appealing and user-friendly. Here are the steps to add basic styles to our calculator:

Creating a CSS File

Firstly, we need to create a new CSS file to store all the style rules that we will apply to the HTML elements of the calculator. Create a new file named styles.css inside your project folder.

Writing CSS

Next, we will write some basic CSS rules to style the calculator. We will add styles for elements such as body, calculator container, buttons, and text inputs. Add the following code into the styles.css file:

body {
    font-family: Arial, sans-serif;
    text-align: center;
    margin-top: 50px;
}

.calculator {
    width: 300px;
    margin: 0 auto;
    border: 1px solid #ccc;
    padding: 10px;
    border-radius: 5px;
    background-color: #f2f2f2;
}

.calculator input[type="button"] {
    width: 60px;
    height: 60px;
    font-size: 20px;
    margin: 5px;
    cursor: pointer;
    border: none;
    border-radius: 5px;
    background-color: #e0e0e0;
}

.calculator input[type="text"] {
    width: 100%;
    height: 60px;
    font-size: 30px;
    text-align: right;
    padding-right: 10px;
    box-sizing: border-box;
    margin-bottom: 10px;
}

Explanation of the CSS code above:

  • body: Sets the default font to Arial and sans-serif, centers the text, and provides a top margin of 50px to create space above the calculator.

  • .calculator: Sets the width of the calculator to 300px, centers it using auto margins, adds a border, padding, and border-radius to round its corners. The background color of the calculator is set to light gray.

  • .calculator input[type="button"]: Specifies the size of the calculator buttons, font size, margin between buttons, removes default borders, adds border-radius for rounded corners, and sets a light gray background color.

  • .calculator input[type="text"]: Defines the size of the text input, font size, right-aligns the text, adds padding on the right side, uses box-sizing to include padding in the element size calculation, and adds bottom margin to create space between the text input and the buttons.

By adding this CSS code, the calculator's appearance will become more appealing and user-friendly. Next, we will link this CSS file to the main HTML file so that the styles we've created can be applied to the calculator.

Adding Logic with JavaScript

Next, we will add logic to our calculator using JavaScript. This step is crucial as it will provide functionality to the calculator, allowing users to perform basic mathematical operations such as addition, subtraction, multiplication, and division. We will go through several steps to achieve this, including creating a new JavaScript file, linking it to the HTML file, and writing JavaScript code to implement the calculator's logic.

Creating the JavaScript File

The first step is to create a new JavaScript file. This file will contain all the JavaScript code needed to run the calculator. Create a file named script.js in your project folder. This file will be filled with functions necessary for the calculator.

Linking the JavaScript File

After creating the JavaScript file, we need to link it to the HTML file so that the browser can execute the JavaScript code. This is done by adding a <script> tag at the bottom of the <body> element in our HTML file, like this:

<script src="script.js"></script>

By adding this line, we ensure that the file script.js will be loaded and executed when the web page is opened.

Writing JavaScript

Now it's time to write JavaScript code to add logic to our calculator. We will create three main functions: addToDisplay, clearDisplay, and calculate.

  • addToDisplay(value): This function will add a value to the calculator display each time the user presses a button.

  • clearDisplay(): This function will clear all values from the calculator display.

  • calculate(): This function will evaluate the mathematical expression on the calculator display and display the result.

Here is the implementation of these functions:

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

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

function calculate() {
    var display = document.getElementById('display');
    var result = eval(display.value);
    display.value = result;
}
  • addToDisplay(value): This function takes a parameter value and adds it to the element with id display. Each time the button is pressed, the value of that button will be added to the calculator display.

  • clearDisplay(): This function clears the calculator display by setting the value of the element with id display to an empty string.

  • calculate(): This function retrieves the mathematical expression from the calculator display, computes the result using the eval() function, and displays the result on the calculator display.

By adding this code to the script.js file, our calculator can now accept input, clear input, and perform basic calculations. The next step is to test this functionality to ensure that the calculator works as expected.

Testing the Calculator

After completing the calculator coding, the next step is to ensure that all functionalities work correctly through comprehensive testing. In this section, we will perform basic testing to verify that the calculator functions as expected. This testing includes verifying numeric input, arithmetic operations, and calculation results.

Additionally, we will also handle common errors that may arise during calculator usage. This is crucial to ensure that the calculator is bug-free and can provide accurate results to users. Thus, we can ensure that the calculator we have created not only functions but is also reliable and ready for use.