JavaScript Operators
By Flavio Copes
Learn how JavaScript operators combine expressions into more complex ones, from binary operators like addition to unary operators and the ternary operator.
Operators allow you to get one or more simple expressions and combine them to form a more complex expression.
Take this line:
const total = price * quantity
Here * is an operator. The values it works on, price and quantity, are called operands. The operator takes those two operands and produces a new value.
We can classify operators based on the number of operands they work with.
Binary operators
Most operators work with 2 operands. We call them binary operators:
- Addition (
+) - Subtraction (
-) - Division (
/) - Remainder (
%) - Multiplication (
*) - Exponentiation (
**) - Assignment (
=) - Comparison operators (
<,<=etc) - Equality checks (
==,!==etc) - Logical
andandor instanceofin
They don’t all produce numbers. Comparison and equality operators produce a boolean:
const age = 18
age >= 18 // true
And that boolean is what you use in if statements and loops.
Unary operators
Some operators work with a single operand. We call them unary operators:
- Increment (
++) - Decrement (
--) - Unary negation (
-) - Unary plus (
+) - Logical not (
!) newdeletetypeofawait- The spread operator
For example, ! flips a boolean:
const loggedIn = false
!loggedIn // true
And typeof tells you the type of a value:
typeof 'flavio' // 'string'
The ternary operator
Just one operator works with 3 operands: the ternary operator. It’s a compact way to pick between two values based on a condition:
const age = 18
const status = age >= 18 ? 'adult' : 'minor'
Be careful with precedence
When you combine multiple operators in one expression, JavaScript applies them in a fixed order. Multiplication runs before addition, like in math:
2 + 3 * 4 // 14, not 20
My advice is to not memorize the precedence rules. Use parentheses to make the order explicit:
(2 + 3) * 4 // 20
Anyone reading the code (including you, in six months) will thank you.
Related posts about js: