Arithmetic Operators in JavaScript

SEARCH THIS SITE

Custom Search



The use of arithmetic operators in Javascript explained through examples.

Addition (+), Subtraction(-), Multiplication(*) and Division(/) in Javascript

The operators + , - , * and / are used to write arithmetic expressions as shown in the sample program below. Run the sample program below and check that the answer displayed is 0.

<!DOCTYPE html>
<html>
<body>
<script>
var x = 2, y = 3, z = 4, w;
w = 1.5 + y*(x - 4)/z;
alert(w);
</script>
</body>
</html>

Modulo Operator in Javascript

The modulo operator written as % is used to find the remainder of the division of two numbers. Run the sample program below and check that the answer displayed is 3 which is the remainder of 27 divided by 4. (27 = 4 * 6 + 3)

<!DOCTYPE html>
<html>
<body>
<script>
var x = 27%4;
alert(x);
</script>
</body>
</html>

Increment / Decrement Operator in Javascript

To increment a number x by 1 write it ++x. Run the sample program below and check that the answer displayed is 4.7 which is 3.7 + 1. To decrement a number by 1 write it - -x.

<!DOCTYPE html>
<html>
<body>
<script>
var x = 3.7;
var y = ++x;
alert(y);
</script>
</body>
</html>


Books and References

1 - A Smarter Way to Learn JavaScript: The new approach that uses technology to cut your effort in half - Mark Myers
2 - JavaScript and JQuery: Interactive Front-End Web Development 1st Edition - Jon Duckett - ISBN-13: 978-1118531648
3 - A Smarter Way to Learn HTML & CSS: Learn it faster. Remember it longer. (Volume 2) - Mark Myers
4 - http://www.w3schools.com/js/default.asp - JavaScript Tutorial