An Easy Guide to Build a Calculator App in JavaScript

Ever wondered how to build a calculator app in JavaScript? This is an exceptional article to learn how to build a simple calculator application using HTML/CSS and JavaScript. This is assuming that you know the basics like HTML tags and CSS styling. In this article on Calculator in JavaScript, the text editor you will use is VS Code. So, here’s a live demo of the calculator you will build after you follow the step-by-step guide. 

Calculator_JavaScript

Now that you know what’s in store for you, let’s begin. 

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

A Guide to Build a Simple Calculator

Here, this demo has created a folder called Calculator which holds three files, viz., index.html, calc.js, and calc.css. 

Initial HTML Code to Include the .js and .css files 

In this step, you write the head tag's initial code and include the .js and .css files. 

<!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">

    <script src="./calc.js" type="text/javascript"></script> 

    <link rel="stylesheet" href="calc.css">

    <title>Document</title>

</head>

Input the Digits And Operators

This step creates buttons for digits from 0 to 9 and operators like +,-,*,/, and = 

<body>

    <h1 style="text-align:center">Calculator App</h1>

    <div class="container">

    <br>

    <table>

        <tr>

            <td colspan="3"><input type='text' id='result' class ='screen' style="text-align: right;"></td>

            <td>

                <input type='button' value = 'C' onclick="clearScreen()" class="clear"/>

            </td>

        </tr>

    </table>

    <div class="keys">

    <input type="button" value="7" class="button" onClick="display('7')"></input>

    <input type="button" value="8" class="button " onClick="display('8')"></input>

    <input type="button" value="9" class="button" onClick="display('9')"></input>

    <input type="button" value="/" class="operator" onClick="display('/')"></input>

    <input type="button" value="4" class="button" onClick="display('4')"></input>

    <input type="button" value="5" class="button" onClick="display('5')"></input>

    <input type="button" value="6" class="button" onClick="display('6')"></input>

    <input type="button" value="*" class="operator" onClick="display('*')"></input>

    <input type="button" value="1" class="button" onClick="display('1')"></input>

    <input type="button" value="2" class="button" onClick="display('2')"></input>

    <input type="button" value="3" class="button" onClick="display('3')"></input>

    <input type="button" value="-" class="operator" onClick="display('-')"></input>

    <input type="button" value="0" class="button" onClick="display('0')"></input>

    <input type="button" value="." class="button" onClick="display('.')"></input>

    <input type="button" value= "=" class="button equal-sign" onClick="solve()"></input>

    <input type="button" value="+" class="operator" onClick="display('+')"></input>

</div> 

</div>

</body>

Here, you have to make use of the input tag with the type button and a click event. The text box to display the digits and the output value is given the id “result”. This id is used in functions like clearScreen(), Display() and Solve(). These functions perform as their name suggests. It provides the function definition in the .js file. 

Without the styling, the output of the above code will look like this. 

Calculator_JS.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Add the Styling In the .css file

To beautify what you see on the screen, styling is crucial. Here’s the styling you could add to your application. If you prefer a fresh look, you can modify it accordingly. 

.container {

    border: 1px solid #cccccc;

    box-shadow: 10px 10px 30px 0px rgba(0,0,0,0.75);

    border-radius: 20px;

    position: absolute;

    top: 55%;

    left: 50%;

    transform: translate(-50%, -50%);

    width: 450px;

    height: 400px;

}

.keys {

    display: grid;

    grid-template-columns: repeat(4, 1fr);

    grid-gap: 10px;

    padding: 10px;

    margin:auto;

}

.button {

    height: 60px;

    padding: 5px;

    background-color: #fff;

    border-radius: 3px;

    border: 1px solid #c4c4c4;

    background-color: transparent;

    font-size: 2rem;

    color: #333;

    background-image: linear-gradient(to bottom, transparent, transparent 50%, rgba(0,0,0,.04));

    box-shadow: inset 0 0 0 1px rgba(255,255,255,.05), inset 0 1px 0 0 rgba(255,255,255,.45), inset 0 -1px 0 0 rgba(255,255,255,.15), 0 1px 0 0 rgba(255,255,255,.15);

    text-shadow: 0 1px rgba(255,255,255,.4);

}

.button:hover {

    background-color: #eaeaea;

}

.operator {

    color: #fff;

    background-color: #eebb24;

}

.clear {

    background-color: #f0595f;

    border-color: #b0353a;

    color: #fff;

    width: 80px;

    height: 30px;  

}

.clear:hover {

    background-color: #f17377;

}

.equal-sign {

    background-color: #25a8e0;

    border-color: #25a8e0;

    color: #fff;

}

.equal-sign:hover {

    background-color: #4e9ed4;

}

.screen{

    background-color:rgb(171, 219, 231);

    justify-content: left;

    color: black;

    font-size: medium;

    width: 50%;

    height: 30%;

    cursor: default;

    padding: 10px; 

    padding-left: 40%;

    margin: auto;

    margin-bottom: 10px;

}

After adding the styling, your application will look like this. 

JavaScript_Calculator

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Handing the Input Provided by the User

All the input given by the user must be accepted and processed to provide the necessary output. As mentioned, you are performing three different actions, displaying the values, solving the expressions, and clearing the textbox. Here’s the code to be written in the calc.js file

display() function

function display(val){

    document.getElementById('result').value += val

    return val

}

Calculator_Display

This function accepts the values clicked as a parameter and returns the same to the textbox. The value could be a digit, a decimal point, or an operator except ‘=’. 

solve() function

function solve(){

    let x = document.getElementById('result').value

    let y = eval(x);

    document.getElementById('result').value = y

    return y

}

Calculator_Solve.

The solve() method is called when the user clicks on the ‘=’ operator. The variable x accepts the mathematical expression provided by the user. This expression is evaluated and stored in the variable y. The result is displayed in the textbox. 

clearScreen()

This function is called when the user clicks on the C or the clear button. 

function clearScreen(){

    document.getElementById('result').value = ''

}

The value of the result is set to an empty string. 

You can now open your browser to view the final output. 

Calculator_JavaScript

And VOILA!!! You have successfully created a calculator application using JavaScript. 

We offer complete Job Guarantee and money-back if you don't secure a job within 6 months of graduation. Get interview ready with intense and comprehensive career mentoring sessions in our Full Stack Java Developer Program. Enroll TODAY!

Final Thoughts 

We hope you found this article on Calculator in JavaScript helpful. If you wish to learn JavaScript and make a career as a front-end developer, then gaining certification is highly recommended.

Simplilearn's Java Certification Trainingcourse helps master the JavaScript programming language in an all-inclusive training program that includes complete JavaScript fundamentals, jQuery, Ajax, and more. You will also have the opportunity to apply your skills by building a real-time chat application.

If you have any queries or feedback, drop a comment in the comments section of the article. Our experts will get back to you ASAP! 

About the Author

Chinmayee DeshpandeChinmayee Deshpande

Chinmayee is a Research Analyst and a passionate writer. Being a technology enthusiast, her thorough knowledge about the subject helps her develop structured content and deliver accordingly.

View More
  • Acknowledgement
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.