Arithmetics in JavaScript

Like other languages JavaScript can also perform arithmetic operation of numbers.

For examples
<script>
var a=50;
var b=20;
var c=a+b;
alert(c);
</script>

In this little script addition is performed and value of 70 is assigned to variable c and displaced in alert message as shown in blow figure.


Similarly other arithmetic operations can also be performed in Java Script.

For examples we can also write:

alert(2 + 2);

This displays the messge "4" in an alert box.

When it sees a math expression, JavaScript always does the math and delivers the result.
Here's a statement that subtracts 24 from 12, assigning -12 to the variable.

var popularNumber = 12 - 24;

This one assigns the product of 3 times 12, 36, to the variable.

var popularNumber = 3 * 12;

In this one, the number 10 is assigned to a variable. Then 1 is added to the variable, and
the sum, 210, is assigned to a second variable.

As usual, you can mix variables and numbers.

 var num = 10;

 var popularNumber = num + 200;

You can also use nothing but variables.

var num = 10;
var anotherNum = 1;
var popularNumber = num + anotherNum;

The arithmetic operators I've been using, +, -, *, and /, are undoubtedly familiar to you.
This one may not be:

var whatsLeftOver = 10 % 3;




% is the modulus operator. It doesn't give you the result of dividing one number by
another. It gives you the remainder when the division is executed.
If one number divides evenly into another, the modulus operation returns 0. In the
following statement, 0 is assigned to the variable.

There are several specialized math expressions you need to know. Here's the first one.

num++;

This is a short way of writing...

num = num + 1;

It increments the variable by 1.

You decrement using minuses instead of pluses.

num--;

You can use these expressions in an assignment. But the result may surprise you.

1 var num = 1;
2 var newNum = num++;

In the example above, the original value of num is assigned to newNum, and num is
incremented afterward. If num is originally assigned 1 in the first statement, the second
statement boosts its value to 2. newNum gets the original value of num, 1.
If you place the pluses before the variable, you get a different result.

1 var num = 1;
2 var newNum = ++num;

In the statements above, both num and newNum wind up with a value of 2.
If you put the minuses after the variable, the new variable is assigned the original value,
and the first variable is decremented.

1 var num = 1;
2 var newNum = num--;

num is decremented to 0, and newNum gets the original value of num, 1.

But if you put the minuses before the variable, newNum is assigned the decremented, not
the original, value. Both num and newNum wind up with a value of 0.

1 var num = 1;
2 var newNum = --num;