Contact Our Development Team
Free Code Tutorials & Open Source Code
Simple Operations
Tutorials > JavaScript > Simple Operations
Arithmetic Operators
You're already familiar with basic mathematical operators such as + and -. These can be used in JavaScript just as they would in everyday usage:
x = 5;
y = x + 2;
z = 7 - y;

Here's a list of all the arithmetic operators available in JavaScript, along with simple examples of their usage:

Operator Meaning Example Result
+ Add x=4+5 x=9
- Subtract x=9-5 x=4
* Multiply x=2*3 x=6
/ Divide x=6/3
x=1/4
x=2
x=0.25
% Modulus (Division remainder) x=3/2
x=10/2
x=1
x=0
++ Increment x++
x=++y
x=y++
x=x+1
y=y+1 then x=y
x=y then y=y+1
-- Decrement x--
x=--y
x=y--
x=x-1
y=y-1 then x=y
x=y then y=y-1

Operators can be combined in a single statement. For example, x=2+4*7 is perfectly valid, and would evaluate to 30. JavaScript performs calculations according to the standard order of operations: exponents and roots, followed by multiplication and division, then addition and subtraction. As in normal arithmetic, brackets can be used to change the order of operations - x=(2+4)*7 would evaluate to 42.

Assigning Values to Variables

We've already seen the use of the = assignment operator, which simply sets the variable on the left-hand side to the value on the right-hand side. JavaScript offers a number of other assignment operators. In all the examples below, x has the initial value of 10:

Operator Example Meaning Result
= x=5 Equals x=5
+= x+=5 x=x+5 x=15
-= x-=5 x=x-5 x=5
*= x*=5 x=x*5 x=50
/= x/=5 x=x/5 x=2
%= x%=5 x=x%5 x=0
Page Responses
Currently there have been no responses to this page...
If you have anything to contribute to this tutorial, found a bug, or know a better way of achieving the same goal, please leave your response below.
     
Copyright ©2009, Wired IDS Ltd. | Licensed under Creative Commons Attribution Share-Alike | Load time: 0.306 seconds