Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript Operators: Complete Guide

JavaScript operators are symbols that perform actions on values and variables, from simple math to advanced safe data access.

If you understand operators well, you can write clearer logic, avoid subtle bugs, and express intent more directly in your code.

Why We Need It

Operators appear in almost every line of JavaScript. Confusing precedence, equality rules, or short-circuiting can lead to bugs that are hard to spot.

Learning operators gives you reliable building blocks for calculations, decisions, defaults, and safe data access.

Syntax

// Arithmetic
a + b, a - b, a * b, a / b, a % b, a ** b
// Assignment
x = y, x += y, x -= y, x *= y, x /= y
// Comparison
a === b, a !== b, a > b, a < b, a >= b, a <= b
// Logical
a && b, a || b, !a
// Ternary
condition ? valueIfTrue : valueIfFalse
// Nullish / Optional
value ?? fallback, obj?.prop, obj?.method?.()
// Bitwise
a & b, a | b, a ^ b, ~a, a << b, a >> b, a >>> b

Basic Example

1. Arithmetic + Assignment

let total = 0;

total += 25; // add item price
const tax = total * 0.1;
const final = total + tax;

console.log(final);

Arithmetic and assignment operators handle running totals and derived values.

Real World Example

2. Comparison + Logical

const age = 21;
const hasId = true;

const canEnter = age >= 18 && hasId;
console.log(canEnter); // true

Combine comparison and logical operators to express clear rules.

Multiple Use Cases

Everyday Calculations

Arithmetic operators power totals, averages, prices, and time math. You use them anytime you add, subtract, multiply, divide, or work with remainders.

When expressions get longer, precedence decides the evaluation order. Parentheses keep intent obvious for you and your teammates.

  • Use `+` for numeric addition and string concatenation.
  • Use `**` for powers and `%` for remainders.
  • Wrap complex expressions in parentheses for clarity.

Decision Making

Comparison and logical operators are the foundation of conditionals. They help you answer questions like �Is this user logged in?� or �Is the value in range?�

Combine them to create readable rules for UI states, validation, and branching logic.

  • Prefer strict equality `===` over `==` to avoid coercion surprises.
  • Use `&&` for guards and `||` for fallbacks.
  • Use `!` to invert a boolean condition.

Safer Defaults

Modern operators like nullish coalescing (`??`) and optional chaining (`?.`) prevent runtime errors and make defaults explicit.

They shine when dealing with API responses or optional config values.

  • Use `??` to keep 0, false, and empty strings intact.
  • Use `?.` to safely access nested data.
  • Combine both for resilient data access in UIs.

Low-Level Control

Bitwise operators are less common but useful for flags, permissions, and performance-sensitive math.

They work on 32-bit integers, so keep that in mind when mixing with large numbers.

  • Use `|` to combine flags and `&` to test them.
  • Use shifts for quick powers-of-two operations.
  • Avoid bitwise ops on floating-point data.

More Examples

3. Nullish + Optional Chaining

const user = { profile: { name: "Riya" } };

const name = user?.profile?.name ?? "Guest";
console.log(name);

Optional chaining prevents crashes and nullish coalescing provides safe defaults.

4. Ternary Operator

const score = 72;
const badge = score >= 70 ? "Pass" : "Retry";

console.log(badge);

The ternary operator gives compact, readable conditional values.

Comparison

Without

// Without clear operators
let isAdult = false;
if (age >= 18) {
  isAdult = true;
}

let label = "";
if (user && user.profile && user.profile.name) {
  label = user.profile.name;
} else {
  label = "Guest";
}

With

// With modern operators
const isAdult = age >= 18;
const label = user?.profile?.name ?? "Guest";

Common Mistakes and Fixes

Using loose equality everywhere

Stick to strict equality (`===`) unless you explicitly want coercion.

Overwriting falsy values

Use `??` instead of `||` when 0 or empty strings are valid.

Ignoring precedence

Use parentheses to make complex expressions unambiguous.

Unsafe property access

Use optional chaining (`?.`) when values may be null or undefined.

Misusing bitwise operators

Remember bitwise ops convert to 32-bit integers and can lose precision.

Interview Questions

Why is strict equality preferred in JavaScript?

It avoids implicit type coercion, making comparisons more predictable.

What is operator precedence?

It defines the order in which operators are evaluated in an expression.

How does short-circuiting help performance?

It skips unnecessary evaluation once the outcome is known.

Practice Problem

Practice: Build a small scoring rule that uses arithmetic, comparison, and a ternary operator to return a grade label.

const score = 78;
// TODO: return "A", "B", or "C"

One Possible Solution

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

Frequently Asked Questions

What is the difference between == and ===?

`==` performs type coercion before comparing. `===` compares both value and type, so it is safer in most cases.

When should I use ?? instead of ||?

Use `??` when you only want to fallback for `null` or `undefined`, not for other falsy values like 0 or "".

What does short-circuiting mean?

Logical operators stop evaluating as soon as the result is known. This enables guard clauses and efficient defaults.

Are bitwise operators still useful?

Yes, especially for flags, permissions, and compact state storage, but they are less common in everyday UI code.

Try It Yourself

Try the operator examples in our JavaScript compiler and tweak the values to see how outputs change.