Arithmetic Operations
A typical arithmetic operation operates on two numbers.
The two numbers can be literals:
Example
var x = 100 + 50;
or variables:
Example
var x = a + b;
or expressions:
Example
var x = (100 + 50) * a;
Subtracting
The subtraction operator (
-
) subtracts numbers.Example
var x = 5;
var y = 2;
var z = x - y;
Multiplying
The multiplication operator (
*
) multiplies numbers.Example
var x = 5;
var y = 2;
var z = x * y;
Dividing
The division operator (
/
) divides numbers.Example
var x = 5;
var y = 2;
var z = x / y;
Remainder
The modulus operator (
%
) returns the division remainder.Example
var x = 5;
var y = 2;
var z = x % y;
In arithmetic, the division of two integers produces a quotient and a remainder.
In mathematics, the result of a modulo operation is the remainder of an arithmetic division.
In mathematics, the result of a modulo operation is the remainder of an arithmetic division.
Incrementing
The increment operator (
++
) increments numbers.Example
var x = 5;
x++;
var z = x;
Decrementing
The decrement operator (
--
) decrements numbers.Example
var x = 5;
x--;
var z = x;
Exponentiation
The exponentiation operator (
**
) raises the first operand to the power of the second operand.Example
var x = 5;
var z = x ** 2; // result is 25
x ** y produces the same result as
Math.pow(x,y)
:Example
var x = 5;
var z = Math.pow(x,2); // result is 25
Operator Precedence
Operator precedence describes the order in which operations are performed in an arithmetic expression.
Example
var x = 100 + 50 * 3;
Is the result of the example above the same as 150 * 3, or is it the same as 100 + 150?
Is the addition or the multiplication done first?
As in traditional school mathematics, the multiplication is done first.
Multiplication (
*
) and division (/
) have higher precedence than addition (+
) and subtraction (-
).