Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript Operators: Arithmetic, Comparison, Logical, and More

Operators define how values are calculated, compared, and combined. Clear operator usage avoids silent logic bugs.

Why this matters

Many bugs come from wrong operator choice, precedence confusion, or type coercion in comparisons.

Comparison and Logical Operators

Use strict equality operators (===, !==) to avoid implicit type conversion.

Logical operators (&&, ||, !) are used for guard clauses and condition composition.

Short-circuit behavior can simplify fallback values and safe access flows.

Assignment, Nullish, and Ternary Operators

Compound assignment operators (+=, -=, *=) reduce repetitive code.

Nullish coalescing (??) handles null/undefined while preserving valid falsy values like 0 or empty string.

Ternary operator is useful for concise branching, but nested ternary should be avoided for readability.

Code Examples

Strict vs Loose Equality

console.log(5 == "5");   // true
console.log(5 === "5");  // false
console.log(false == 0); // true
console.log(false === 0);// false

Use strict checks in production code for predictable behavior.

Nullish Coalescing vs OR

const count = 0;
console.log(count || 10); // 10
console.log(count ?? 10); // 0

?? is better when 0/empty-string are valid values.

Ternary for UI Labels

const score = 84;
const grade = score >= 90 ? "A" : score >= 75 ? "B" : "C";
console.log(grade);

Use ternary for compact decisions, keep complexity controlled.

Common Mistakes and Fixes

Using loose equality everywhere

Prefer strict equality unless coercion is intentionally needed.

Confusing || and ??

Use ?? when null/undefined fallback is intended, not all falsy values.

Overusing nested ternary

Refactor to if/else for readability when branching grows.

Frequently Asked Questions

Should I ever use == in JavaScript?

In most application code, use === for safer and clearer comparisons.

What is short-circuit evaluation?

Logical operators stop evaluation once result is determined.

When to use ?? instead of ||?

Use ?? when 0, false, or empty string should remain valid values.

Is ternary faster than if/else?

Performance difference is negligible; choose based on readability.

Related JavaScript Topics