JavaScript Operators Explained — Step-by-Step Guide with Examples
JavaScript operators are symbols that perform operations on values — like a calculator that can add, compare, and combine data in your code.
What You’ll Learn
- All JavaScript operator types: arithmetic, assignment, comparison, logical, and special operators
- How operator precedence determines evaluation order
- The difference between
==and===,||and?? - How to use spread, optional chaining, and ternary operators safely
Why Operators Matter
Every line of code you write involves operators — adding numbers, comparing values, combining conditions. In the Doda Browser, operators check if extensions are compatible, validate user permissions, and calculate memory usage. The Durga Antivirus Pro dashboard uses comparison operators to trigger alerts when CPU usage exceeds 90%. Without operators, your code would just be a list of static values.
Learning Path
flowchart LR
A[JavaScript Basics] --> B[JavaScript Operators]
B --> C[Control Flow]
C --> D[Functions]
C --> E[Strings & Numbers]
B --> F[You Are Here]
What Is an Operator?
An operator is a symbol that tells JavaScript to perform a specific action. Think of it like the buttons on a calculator:
5 + 3 → The + operator tells JS to add
10 > 5 → The > operator tells JS to compareThe values an operator works on are called operands. In 5 + 3, 5 and 3 are operands.
Arithmetic Operators
These do math — exactly like a calculator:
let a = 10, b = 3;
console.log(a + b); // 13 — addition
console.log(a - b); // 7 — subtraction
console.log(a * b); // 30 — multiplication
console.log(a / b); // 3.333... — division
console.log(a % b); // 1 — modulus (remainder)
console.log(a ** b); // 1000 — exponentiation (10³)
Why modulus matters: The % operator gives the remainder after division. You use it to check if a number is even (num % 2 === 0), cycle through array indices, or implement pagination.
Increment and Decrement
let x = 5;
console.log(x++); // 5 — post-increment: returns x THEN adds 1
console.log(x); // 6 — now x is 6
console.log(++x); // 7 — pre-increment: adds 1 THEN returns
Anticipating confusion: Why does x++ return 5 when x was 5? Because post-increment says “give me the current value, then increment.” Pre-increment says “increment first, then give me the new value.” Think of it like: “I’ll pay you after the work” vs “I’ll pay you before the work.”
Assignment Operators
These assign values to variables. The basic one is =, but compound versions combine an operation with assignment:
let x = 10; // Basic assignment
x += 5; // x = x + 5 → 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
x **= 3; // x = x ** 3 → 8
Why these exist: x += 5 is shorter than x = x + 5. It also makes code clearer — “add 5 to x” is more readable.
Comparison Operators
Comparison operators produce a boolean (true or false). They’re the “questions” your code asks:
// Strict operators (always use these)
console.log(5 === '5'); // false — different types
console.log(5 !== '5'); // true — 5 is not equal to '5'
// Loose operators (avoid)
console.log(5 == '5'); // true — converts types first (dangerous)
console.log(5 != '5'); // false — type coercion again
// Relational
console.log(5 > 3); // true
console.log(5 < 3); // false
console.log(5 >= 5); // true
console.log(5 <= 4); // false
The golden rule: Always use === (strict equality) and !== (strict inequality). Never use == or !=. Why? Because == converts types before comparing, so 5 == '5' is true — which is almost never what you want. It’s like saying “a banana equals a yellow car” because they’re both yellow.
Logical Operators
Logical operators combine or invert boolean values:
// AND (&&) — both sides must be true
console.log(true && true); // true
console.log(true && false); // false
// OR (||) — at least one side must be true
console.log(true || false); // true
console.log(false || false); // false
// NOT (!) — inverts the value
console.log(!true); // false
console.log(!false); // true
Short-Circuit Evaluation
JavaScript evaluates && and || from left to right and stops as soon as it knows the result:
const user = null;
const name = user && user.name; // null — stops at user (falsy)
const greeting = user || 'Guest'; // 'Guest' — user is falsy, uses default
This is commonly used in React for conditional rendering:
{user && <Profile name={user.name} />}Nullish Coalescing (??)
The ?? operator is like || but more precise. It returns the right side only when the left is null or undefined:
const value = null ?? 'default'; // 'default'
const value2 = 0 ?? 'default'; // 0 — 0 is not null or undefined
const value3 = '' ?? 'default'; // '' — empty string is valid
Why this matters: With ||, 0 ?? 'default' would give 'default' because 0 is falsy. But 0 is a valid value (e.g., a temperature reading). The ?? operator treats 0, '', and false as valid.
Ternary Operator
A compact if/else in one line:
const age = 20;
const status = age >= 18 ? 'Adult' : 'Minor';
// condition ? ifTrue : ifFalse
Read it aloud: “Is age >= 18? If yes, return ‘Adult’. If no, return ‘Minor’.”
Optional Chaining (?.)
Safely access nested properties without crashing:
const user = { address: { city: 'NYC' } };
console.log(user?.address?.city); // 'NYC'
console.log(user?.billing?.address); // undefined — no error!
Without ?., accessing user.billing.address would throw Cannot read property 'address' of undefined. This is a lifesaver when working with API responses where data structures vary.
Spread Operator (...)
The spread operator expands an array or object into its elements:
// Copy an array
const original = [1, 2, 3];
const copy = [...original]; // [1, 2, 3] — new array
// Merge arrays
const merged = [...original, 4, 5]; // [1, 2, 3, 4, 5]
// Copy an object
const obj = { a: 1, b: 2 };
const objCopy = { ...obj, c: 3 }; // { a: 1, b: 2, c: 3 }
Why spread is useful: It creates a new copy instead of modifying the original. This is critical in React where state must be immutable.
Operator Precedence
Precedence determines which operator runs first — like multiplication before addition in math:
console.log(2 + 3 * 4); // 14 — multiplication first (3*4=12, then 2+12=14)
console.log((2 + 3) * 4); // 20 — parentheses override precedence
Rule of thumb: When in doubt, use parentheses. They make your intent clear and prevent bugs.
Common Mistakes
1. Using = instead of === in conditions
if (x = 5) { } // Assigns 5 to x, then evaluates truthy — ALWAYS runs
Fix: Always use === for comparison. Train your muscle memory.
2. Confusing || with ??
const count = 0 || 10; // 10 — 0 is falsy, so || uses default
const count = 0 ?? 10; // 0 — ?? only falls back for null/undefined
Use ?? when 0, '', and false are valid values.
3. Forgetting that && has higher precedence than ||
true || false && false; // true — && evaluated first, so false && false = false, then true || false = true
4. Using == for comparison
'5' == 5 // true — type coercion you didn't ask for
'5' === 5 // false — correct, types don't match
5. Side effects in conditions
if (x++ > 10) { } // Increments x AND compares — confusing
Increment separately for clarity.
Practice Questions
What’s the difference between
==and===?==compares values after type coercion.===compares without coercion (strict).What does
0 ?? 'default'return? Why?0— because??only falls back fornullorundefined, and0is neither.What’s the result of
2 + 2 * 3?8— multiplication has higher precedence, so2 * 3 = 6, then2 + 6 = 8.How does optional chaining prevent errors? It returns
undefinedif any part of the chain isnullorundefinedinstead of throwing a TypeError.
Challenge: Create an object user with nested profile.address.city. Access the city safely using optional chaining. Then use the nullish coalescing operator to provide a default value of “Unknown” when the city is missing.
FAQ
Try It Yourself
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS Operators Playground</title>
<style>
body { font-family: Arial, sans-serif; padding: 2rem; }
pre { background: #f4f4f4; padding: 1rem; border-radius: 5px; }
</style>
</head>
<body>
<h1>JavaScript Operators Sandbox</h1>
<pre id="output"></pre>
<script>
const out = document.getElementById('output');
let result = '';
// Arithmetic
result += '--- Arithmetic ---\n';
result += `10 + 3 = ${10 + 3}\n`;
result += `10 % 3 = ${10 % 3}\n`;
result += `2 ** 8 = ${2 ** 8}\n\n`;
// Comparison
result += '--- Comparison ---\n';
result += `5 === "5": ${5 === '5'}\n`;
result += `5 > 3: ${5 > 3}\n\n`;
// Logical
result += '--- Logical ---\n';
result += `true && false: ${true && false}\n`;
result += `null ?? "default": ${null ?? 'default'}\n`;
out.textContent = result;
</script>
</body>
</html>What’s Next
Now that you know operators, learn how to control the flow of your programs:
| Lesson | Description |
|---|---|
| JavaScript Home | Back to the JavaScript hub |
| https://tutorials.dodatech.com/programming-languages/javascript/js-control-flow/ | Control Flow — if/else, loops, switch |
| https://tutorials.dodatech.com/programming-languages/javascript/js-functions/ | Functions — reusable code blocks |
| https://tutorials.dodatech.com/programming-languages/javascript/js-strings-numbers/ | Strings, Numbers & Math |
| React for Beginners | Use operators in React components |
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
What’s Next
Congratulations on completing this Js Operators tutorial! Here’s where to go from here:
- Practice daily — Consistency is more important than long study sessions
- Build a project — Apply what you learned by building something real
- Explore related topics — Check out other tutorials in the same category
- Join the community — Discuss with other learners and share your progress
Remember: every expert was once a beginner. Keep coding!
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro