Values and variables
The JavaScript Arithmetic operators
Learn the JavaScript arithmetic operators, from addition, subtraction, multiplication, and division to remainder, exponentiation, increment, and decrement.
Math shows up in almost every program. JavaScript gives you a familiar set of arithmetic operators.
- Addition (+)
- Subtraction (-)
- Division (/)
- Remainder (%)
- Multiplication (*)
- Exponentiation (**)
- Increment (++)
- Decrement (
--) - Unary negation (-)
- Unary plus (+)
Addition (+)
const three = 1 + 2
const four = three + 1
+ also concatenates strings. Mix types and you get concatenation, not addition:
const three = 1 + 2
three + 1 // 4
'three' + 1 // three1
Subtraction (-)
const two = 4 - 2
Division (/)
Returns the quotient of the first operand and the second:
const result = 20 / 5 //result === 4
const result = 20 / 7 //result === 2.857142857142857
Divide by zero and JavaScript returns Infinity (or -Infinity for negative numerators):
1 / 0 //Infinity
-1 / 0 //-Infinity
Remainder (%)
The remainder is handy for wrapping indices and checking even numbers:
const result = 20 % 5 //result === 0
const result = 20 % 7 //result === 6
Remainder by zero is NaN:
;(1 % 0) - //NaN
(1 % 0) //NaN
Multiplication (*)
Multiply two numbers:
1 * 2 - //2
1 * 2 //-2
Exponentiation (**)
Raise the first operand to the power of the second:
1 ** 2 //1
2 ** 1 //2
2 ** 2 //4
2 ** 8 //256
8 ** 2 //64
** matches Math.pow():
Math.pow(4, 2) == 4 ** 2
Increment (++)
Increment a number. Postfix returns the old value, then increments. Prefix increments first, then returns the new value:
let x = 0
x++ //0
x //1
++x //2
Decrement (--)
Works like increment, but subtracts one:
let x = 0
x-- //0
x //-1
--x //-2
Unary negation (-)
Flip the sign:
let x = 2 - x //-2
x //2
Unary plus (+)
Coerce a value to a number when it is not already one:
let x = 2 + x //2
x = '2' + x //2
x = '2a' + x //NaN
Operator precedence follows school math: multiplication and division before addition, unless parentheses group terms. When in doubt, add parentheses. Future you will thank present you.
The modulo operator is how I check even numbers: n % 2 === 0. It is also how I wrap an index inside a fixed range.
Try 10 % 3, '5' + 2, and +'42' in the console. Predict each result before you run it. You should see 1, '52', and 42.
Lesson completed