Reading Time 5
Number of Words 904
Operators are fundamental building blocks in JavaScript. They allow you to perform operations on values — from arithmetic and comparisons to logical operations and more. Knowing how to use them correctly will make your code more expressive, concise, and correct.
Table of Contents
- What Are Operators?
- Arithmetic Operators
- Assignment & Compound Assignment
- Comparison Operators
- Logical Operators
- Bitwise Operators
- String & Template Operators
- Relational / Other Operators
- Operator Precedence & Associativity
- Real-World Examples
1. What Are Operators?
An operator is a symbol or keyword that tells JavaScript to compute a value from one or more operands (values, variables, or expressions). For example, in a + b, “+” is the operator and a and b are operands.
Operators are categorized by how many operands they take:
- Unary — one operand (e.g.
!a,typeof x) - Binary — two operands (e.g.
a + b,x === y) - Ternary — three operands (only one built-in operator:
condition ? exprIfTrue : exprIfFalse)
2. Arithmetic Operators
These perform numeric calculations:
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ |
Addition | 5 + 3 |
8 |
- |
Subtraction | 10 - 7 |
3 |
* |
Multiplication | 4 * 6 |
24 |
/ |
Division | 12 / 3 |
4 |
% |
Remainder / Modulo | 10 % 3 |
1 |
** |
Exponentiation | 2 ** 3 |
8 |
++ |
Increment by one (unary) | let x = 1; x++; |
x becomes 2 |
-- |
Decrement by one (unary) | let y = 3; y--; |
y becomes 2 |
Example:
let a = 7;
let b = 2;
console.log(a + b); // 9
console.log(a - b); // 5
console.log(a * b); // 14
console.log(a / b); // 3.5
console.log(a % b); // 1
console.log(a ** b); // 49
3. Assignment & Compound Assignment
Assignment operators store values in variables. Compound assignments combine an operator with assignment:
let x = 10;
x += 5; // equivalent to x = x + 5 → now x is 15
x -= 3; // x = x - 3 → 12
x *= 2; // x = x * 2 → 24
x /= 4; // x = x / 4 → 6
x %= 4; // x = x % 4 → 2
Also:
=— basic assignment+=, -=, *=, /=, %=, **=— compound forms
4. Comparison Operators
These compare two values and return a boolean (true or false):
| Operator | Meaning | Example |
|---|---|---|
== |
Loose equality (type conversion happens) | 5 == '5' → true |
=== |
Strict equality (no type conversion) | 5 === '5' → false |
!= |
Loose inequality | 5 != '5' → false |
!== |
Strict inequality | 5 !== '5' → true |
< |
Less than | 3 < 5 → true |
> |
Greater than | 7 > 4 → true |
<= |
Less than or equal | 3 <= 3 → true |
>= |
Greater than or equal | 5 >= 5 → true |
Example:
console.log(4 == '4'); // true
console.log(4 === '4'); // false
console.log(10 >= 9); // true
console.log(3 !== 3); // false
5. Logical Operators
Logical operators let you combine or invert boolean expressions:
&&(AND): returnstrueif both operands aretrue||(OR): returnstrueif at least one operand istrue!(NOT): inverts the boolean value
const a = true;
const b = false;
console.log(a && b); // false
console.log(a || b); // true
console.log(!a); // false
They are often used in conditionals:
const age = 20;
if (age >= 18 && age < 65) {
console.log('Working-age adult');
}
6. Bitwise Operators
Bitwise operators manipulate the binary representations of numbers. These are more advanced, but useful in certain domains (performance, low-level code):
&— AND|— OR^— XOR~— NOT<<— left shift>>— right shift>>>— zero-fill right shift
Example:
// 5 in binary: 0101
// 3 in binary: 0011
console.log(5 & 3); // 1 (0001)
console.log(5 | 3); // 7 (0111)
console.log(5 ^ 3); // 6 (0110)
console.log(~5); // -6 (two’s complement)
console.log(5 << 1); // 10 (1010)
7. String & Template Operators
+— string concatenation:console.log('Hello, ' + 'world!'); // "Hello, world!"- Template literals (backticks) let you embed expressions:
const name = 'Alice'; const age = 30; console.log(`My name is ${name}, and I’m ${age} years old.`); - Tagged templates are more advanced: you can intercept and process template literal parts via a function.
8. Relational / Other Operators
Some other useful operators:
- Ternary operator (conditional):
const status = (score >= 60) ? 'Pass' : 'Fail'; - Nullish coalescing operator (
??): returns the right side if left isnullorundefinedconst a = null; console.log(a ?? 'default'); // "default" - Optional chaining operator (
?.): safely access nested propertiesconst obj = { user: { address: { city: 'Tenerife' } } }; console.log(obj.user?.address?.city); // "Tenerife" console.log(obj.user?.profile?.name); // undefined (no error) - Logical nullish assignment (
??=), AND assignment (&&=), OR assignment (||=)let value; value ??= 100; // value becomes 100 - Comma operator (rarely used): evaluates multiple expressions and returns last
let x = (1, 2, 3); console.log(x); // 3
9. Operator Precedence & Associativity
Operators have priority (precedence) and direction (associativity). For instance, * and / are higher precedence than + and -. Most operators associate left to right, but some (like assignment) are right-to-left.
You can always use parentheses () to explicitly force the order of evaluation:
const result = (2 + 3) * 4; // 20, not 14
10. Real-World Examples
Example 1: Default Value for Missing Parameter
function greet(name) {
name = name || 'Guest';
console.log(`Hello, ${name}`);
}
greet('Bob'); // Hello, Bob
greet(); // Hello, Guest
With newer syntax:
function greet(name = 'Guest') {
console.log(`Hello, ${name}`);
}
Example 2: Using Optional Chaining to Avoid Errors
const user = {
details: {
hometown: 'Santa Cruz'
}
};
console.log(user.details?.hometown); // "Santa Cruz"
console.log(user.profile?.firstName); // undefined (no error)
Example 3: Combining Logical & Nullish Operators
let port = process.env.PORT ?? 3000; // Use env port, or fallback to 3000 if null/undefined
Example 4: Conditional Rendering with Ternary
const isAdmin = true;
const badge = isAdmin ? 'Admin' : 'User';
console.log(badge); // "Admin"