Java/J2EE and SOA (342 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (17 Blogs)
  • Comprehensive Java Course (4 Blogs)
  • Java/J2EE and SOA (339 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

How to Build a JavaScript Calculator?

Last updated on Apr 14,2022 106K Views

22 / 31 Blog from JavaScript

Anyone who starts with a new language has to hassle a lot to learn various modules before working on real industry-specific projects. As we are familiar with a general convention of starting out with our “hello world” programs, there are few programs which we can practice for learning the basics of any language. If you ever tried learning systematically, there is no doubt that you haven’t encountered “building a calculator” phase. So, today we are going to build a basic calculator using JavaScript. The various topics covered here are:

To ease out the process, it is very important that we keep our compilers ready to test things while we are reading the entire post here. Let’s hop in!

JavaScript, better known as the “scripting language” of web pages, can do wonders. A calculator, as we know, will perform our basic operations viz. Addition, Subtraction, Multiplication, and division. For starting out, you should be familiar with HTML and CSS. The section with JavaScript code, we’ll take care of that.

Requirements for building a calculator using JavaScript

  • Integrated Development Environment
  • Local Server/online compiler

If you’re new to website development, you should know that one needs a local server to test out codes before deployment. You can go for wamp, xampp or any other server. For writing your codes, there are so many options: Sublime Text 3, NetBeans, Brackets, etc. Once you’re through with setting up platforms, rest of the work is a cakewalk.

To link various files, you can use the following:

Embedding CSS

  • Inline CSS: When we want to add CSS to our desirable elements, Inline CSS is our call. If you’re new to development, chances are you prefer inline CSS over other types. This is good for a head start, but is certainly not SEO friendly.
  • Internal or Embedded CSS: The CSS properties and rules are set within the same HTML document, specified by <style></style> tags in the <head> section.
  • External CSS: A separate CSS file with the style attributes linked with the main file in the root directory.

In our JavaScript calculator, we’ll be using Internal CSS. First, we need to figure out how many buttons we are going to need. For now, we stick to the minimum viable functionalities for our basic calculator. So, the list of elements are mentioned below:

  1. Display Screen: This will be used for user inputs as well as output results. Even if we develop the complete calculator, there is no point of using it without a real time display screen.
  2. Buttons: We are going to need 17 buttons atleast for a basic calculator:
    • Numbers: The buttons for numbers are required. We need 10 buttons for this category. 1-9 and a 0.
    • Operations: For the four basic operations, we need 4 buttons.
    • Others: For decimal, clear and Result, we need 3 more buttons.

To visualize the calculator, it is better if we consider forming a table. A table is nothing, but rows and columns. The visible parts go into the body section facilitated by CSS. The part which is not visible, is the JavaScript, that goes into <style> section.

The JavaScript Section

This section will include the display, solve and clear functions.

    1. Display Function: This function only displays the user input, followed by results. We just an id which can be called by “document.getElementById”. Here, the id is “edu”.
    2. Solve Function: eval() is a gobal function in JavaScript and has a defined purpose of solving JavaScript codes.
    3. Clear Function: We just need a void in between the quotes to perform this function.

 


<script>
//function for displaying values
function dis(val)
{
document.getElementById("edu").value+=val
&nbsp;}
//function for evaluation
function solve()
{
let x = document.getElementById("edu").value
let y = eval(x)
document.getElementById("edu").value = y
}
//function for clearing the display
function clr()
{
document.getElementById("edu").value = ""
}
</script>

The Visible Section

 

  1. Title: You can write anything here, we prefer calling it “Edureka JavaScript Calculator”.
  2. Table creation: Every row must have buttons and input fuctions. For display screen, we need an input type of text with a <colspan> since we require lengthier strings. The others remain with button types.
  3. The displays are only onclick() functions here, so we use our dis() function here.

 


<!-- create table -->
<body>
<div class = title >Edureka JavaScript Calculator</div>
<table border="1">
<tr>
<td><input type="button" value="c" onclick="clr()"/> </td>
<td colspan="3"><input type="text" id="edu"/></td>
<!-- clr() function will call clr to clear all value -->
</tr>
<tr>
<!-- creating buttons and assigning values-->
<td><input type="button" value="+" onclick="dis('+')"/> </td>
<td><input type="button" value="1" onclick="dis('1')"/> </td>
<td><input type="button" value="2" onclick="dis('2')"/> </td>
<td><input type="button" value="3" onclick="dis('3')"/> </td>
</tr>
<tr>
<td><input type="button" value="-" onclick="dis('-')"/> </td>
<td><input type="button" value="4" onclick="dis('4')"/> </td>
<td><input type="button" value="5" onclick="dis('5')"/> </td>
<td><input type="button" value="6" onclick="dis('6')"/> </td>
</tr>
<tr>
<td><input type="button" value="*" onclick="dis('*')"/> </td>
<td><input type="button" value="7" onclick="dis('7')"/> </td>
<td><input type="button" value="8" onclick="dis('8')"/> </td>
<td><input type="button" value="9" onclick="dis('9')"/> </td>
</tr>
<tr>
<td><input type="button" value="/" onclick="dis('/')"/> </td>
<td><input type="button" value="." onclick="dis('.')"/> </td>
<td><input type="button" value="0" onclick="dis('0')"/> </td>
<!-- Evaluating function call eval()-->
<td><input type="button" value="=" onclick="solve()"/> </td>
</tr>
</table>
</body>

Adding Flavours of CSS

  1. The title element is optional, play with it
  2. The border radius is kept at 10px to give round corners to the elements. The width should be kept at 100% to cover the entire span.
  3. The text-alignment is upto you, feel free.
  4. The RGB colour code: #ff4456

<!-- for styling -->
<style>
.title{
border-radius: 10px;
margin-bottom: 10px;
text-align:center;
width: 210px;
color:#ff4456;
border: solid black 1px;
}
input[type="button"]
{
border-radius: 10px;
background-color:#ff4456;
color: black;
border-color:#ff4456 ;
width:100%;
}
input[type="text"]
{
border-radius: 10px;
text-align: right;
background-color:white;
border-color: black ;
width:100%
}
</style>

 

Now that we have the sections intact, let’s place them and see the result:

Output Screen:

JavaScript Calculator

 

With this, we have come to the end of our article. I hope you understood the easiest way to build a JavaScript calculator.

Now that you know about JavaScript Array Methods, check out the Web developer course by Edureka. Web Development Certification Training will help you learn how to create impressive websites using HTML5, CSS3, Twitter Bootstrap 3, jQuery and Google APIs and deploy it to Amazon Simple Storage Service(S3). 

Got a question for us? Please mention it in the comments section of “The easiest way to build a JavaScript Calculator” and we will get back to you.

Upcoming Batches For Java Certification Training Course
Course NameDate
Java Certification Training Course

Class Starts on 29th October,2022

29th October

SAT&SUN (Weekend Batch)
View Details
Java Certification Training Course

Class Starts on 26th November,2022

26th November

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
Send OTP
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

How to Build a JavaScript Calculator?

edureka.co