JS Tutorial
Arithmetic operators perform operations on integers (literals or variables).
| Operator | Description |
|---|---|
| + | Addition |
| – | Subtraction |
| * | Multiplication |
| ** | Exponentiation (ES2016) |
| / | Division |
| % | Modulus (Remainder) |
| ++ | Increment |
| — | Decrement |
A typical arithmetic procedure works with two numbers.
The two numbers could be literals.
let x = 100 + 50;
or variables:
let x = a + b;
or expressions:
let x = (100 + 50) * a;
The numbers used in an arithmetic operation are referred to as operands.
An operator defines the operation that will be done between the two operands.
| Operand | Operator | Operand |
|---|---|---|
| 100 | + | 50 |
To add numbers, use the addition operator (+):
let x = 5;
let y = 2;
let z = x + y;
The subtraction operator (–) subtracts values.
let x = 5;
let y = 2;
let z = x - y;
The multiplication operator (*) multiplyes numbers.
let x = 5;
let y = 2;
let z = x * y;
The division operator (/) divides numbers.
let x = 5;
let y = 2;
let z = x / y;
The modulus operator (%) returns the division remainder.
let x = 5;
let y = 2;
let z = x % y;
In arithmetic, dividing two integers results in a quotient and a remainder.
In mathematics, a modulo operation yields the remainder of an arithmetic division.
The increment operator (++) increments numbers.
let x = 5;
x++;
let z = x;
The decrement operator (—) decrements numbers.
let x = 5;
x--;
let z = x;
The exponentiation operator (**) multiplies the first operand to the power of the second.
let x = 5;
let z = x ** 2;
x ** y yields the same output as Math.pow(x,y):
let x = 5;
let z = Math.pow(x,2);
Operator precedence refers to the order in which operations are performed in an arithmetic expression.
let x = 100 + 50 * 3;
Is the result of the preceding example the same as 150 * 3, or 100 + 150?
Is addition or multiplication done first?
Multiplication comes first, as it does in regular school mathematics.
Multiplication (*) and division (/) take precedence over addition and subtraction.
In addition, parenthesis can be used to shift the precedence, just like in school mathematics.
When employing parentheses, the operations inside them are computed first:
let x = (100 + 50) * 3;
When multiple operations have the same priority (such as addition and subtraction or multiplication and division), they are computed from left to right.
let x = 100 + 50 - 3;
let x = 100 / 50 * 3;
CodingAsk.com is designed for learning and practice. Examples may be made simpler to aid understanding. Tutorials, references, and examples are regularly checked for mistakes, but we cannot guarantee complete accuracy. By using CodingAsk.com, you agree to our terms of use, cookie, and privacy policy.
Copyright 2010-2024 by Refsnes Data. All Rights Reserved.