Arithmetic operators (JavaScript)

Arithmetic operators perform basic arithmetic operations.

Operation Description
n1 + n2 Returns n1 plus n2.
n1 - n2 Returns n1 minus n2.
n1 * n2 Returns n1 times n2.
n1 / n2 Returns n1 divided byn2.
n1 % n2 Returns n1 modulo n2, that is, the remainder of the integer division of n1 by n2.
n++ Returns n then increments n by 1.
++n Increments n by 1 then returns n.
n-- Returns n then decrements n by 1.
--n Decrements n by 1 then returns n.
-n Negates n.
+n Same as n.

Usage

The result of an arithmetic operation is integer if the result has no fraction, or floating point if the result has a fraction.

Division of two integers with a fractional result yields a floating point value, not an integer with the fraction truncated. For example, 13 / 4 = 3.25. To obtain an integer with the fraction truncated, you might first subtract the modulus from the dividend. For example, (13 - ( 13 % 4)) / 4 = 3.

Examples

This example exercises the arithmetic operators for addition, subtraction, multiplication, and division.
var n = 3;
var m = 4;
var x = 3.1;
var y = 4.2;
print("<<<n = " + n + ">>>");
print("<<<m = " + m + ">>>");
print("<<<x = " + x + ">>>");
print("<<<y = " + y + ">>>");
print("<<<n+m = " + (n + m) + ">>>"); // 7
print("<<<n-m = " + (n - m) + ">>>"); // -1
print("<<<n*m = " + (n * m) + ">>>"); // 12
print("<<<n/m = " + (n / m) + ">>>"); // 0.75
print("<<<n+x = " + (n + x) + ">>>"); // 6.1
print("<<<n-x = " + (n - x) + ">>>"); // -0.10000000000000009
print("<<<n*x = " + (n * x) + ">>>"); // 9.3
print("<<<5*x = " + (5 * y) + ">>>"); // 21
print("<<<n/x = " + (n / x) + ">>>"); // 0.9677419354838709

This example demonstrates the modulus operator and shows how you might do integer division with a remainder.

function p(stuff) {
	print("<<<" + stuff + ">>>");
}

var n = 13;
var m = 4;
p("n = " + n);
p("m = " + m);
var r = n % m;
var q = (n - r) / m;
p("integer n / m = " + q + ", remainder " + r); // 3, 1

This example demonstrates the increment and decrement operators.

function p(stuff) {
	print("<<<" + stuff + ">>>");
}

var ipost = 0;
var ipre = 0;
var dpost = 0;
var dpre = 0;

for(var i = 0; i < 5; i++) {
	p("iteration number " + i); // 0 on first iteration
	p("ipost = " + ipost++); // 0 on first iteration
	p("ipre = " + ++ipre); // 1 on first iteration
	p("dpost = " + dpost--); // 0 on first iteration
	p("ipre = " + --dpre); // -1 on first iteration
}

This example demonstrates the negation operator.

function p(stuff) {
	print("<<<" + stuff + ">>>");
}

var n = 1;
var m = -1;
var nn = -n;
var mm = -m;

p("negative " + n + " = " + nn); // prints -1
p("negative " + m + " = " + mm); // prints 1