JavaScript Tutorial JavaScript Examples JQuery Tutorial CSS Tutorial HTML Tutorial About Us

Lesson 5: Performing Arithmetic Operations

JavaScript is not just a scripting language, it can also perform arithmetic operations. On top of that, it can interact with online users by receiving data from them, operate on the data and then displays the output to the users. The four basic arithmetic operators in JavaScript are shown in the following table:

Table 5.1 Arithmetic Operations
Operation Operator
Addition +
Subtraction -
Multiplication *
Division /
Remainder %
Exponentiation **

For example, 13%5=3 and 4**2=42=16.

Let us construct our first arithmetic program in JavaScript. You can either use a text editor such as Notepad to type in the statements. You can also use Microsoft Frontpage or Dreamweaver to do the job. However, the best free editor I would recommend is Notepad++, which you can download from .

Example 5.1 A Simple Arithmetic Program

var           Number1, // this is the first string input by the user
Number2 , // this is the second string input by the user
Num1 , // numeric value converted from Number1
Num2, // numeric value converted from Number2
difference ,
Number1=window.prompt("Enter your first Integer","0");
Number2=window.prompt("Enter your second integer","0");
Click the Start button initiate the calculation.

The Answers
The sum is 
The difference is 
The product is 
The quotient is 

Let's me explain a bit on the JavaScript codes in Example 5.1. The term document refers to the document object. When a web page is loaded into a browser, it becomes a document object. The document object has methods and properties. The methods we used here is getElementById, which means it returns the element that has the ID attribute with the specified value. The innerHTML property can be used on any element. It is used to replace or retrieve contents in an element. For example, the strong element has the ID of sum, so it is replaced by the value of the sum computed by the JavaScript.

❮ Previous Lesson Next Lesson ❯

Copyright©2008 Dr.Liew Voon Kiong. All rights reserved |Contact|Privacy Policy