JavaScript Operators

JavaScript operators are symbols that perform actions on values, like adding numbers, comparing values or combining conditions. This chapter covers the operators you will use every day.

Arithmetic Operators

The basic math operators are + - * / plus % (remainder) and ** (exponent). ++ and -- add or subtract one.

console.log(10 + 3, 10 - 3, 10 * 3, 10 / 3);
console.log(10 % 3);  // remainder
console.log(2 ** 8);  // power
let n = 5;
n++;
console.log(n);
13 7 30 3.3333333333333335
1
256
6

Assignment Operators

Besides =, there are shortcut operators such as +=, -=, *= and the logical assignments ||=, &&= and ??=.

let total = 100;
total += 50;
total *= 2;
console.log(total);

let title;
title ??= "Untitled"; // assign only if null/undefined
console.log(title);
300
Untitled

Comparison Operators: == vs ===

=== (strict equality) compares value and type. == converts types before comparing, which leads to confusing results. Always prefer === and !==. Other comparisons are <, >, <= and >=.

console.log(5 === 5);     // true
console.log(5 === "5");   // false, different types
console.log(5 == "5");    // true, "5" converted to 5
console.log(0 == false);  // true (surprising)
console.log(3 < 10, "b" > "a");
true
false
true
true
true true

Logical Operators

&& (and), || (or) and ! (not) combine conditions. && and || short-circuit: they stop as soon as the result is known and return one of the operands, not always a boolean.

const age = 20, hasTicket = true;
console.log(age >= 18 && hasTicket);
console.log(!hasTicket);
console.log("" || "default");   // first truthy value
console.log("Ali" && "shown");  // last value if all truthy
true
false
default
shown

Nullish Coalescing and Optional Chaining

?? returns the right side only when the left is null or undefined, unlike || which also replaces 0 and "". ?. reads a property safely, returning undefined instead of throwing when something in the chain is missing.

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

const user = { profile: null };
console.log(user.profile?.email);       // undefined, no error
console.log(user.profile?.email ?? "no email");
10
0
undefined
no email

The Ternary Operator

condition ? a : b is a compact if/else that produces a value.

const stock = 0;
console.log(stock > 0 ? "In stock" : "Sold out");
Sold out

Frequently asked questions

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

=== checks value and type with no conversion. == converts the operands to a common type first. Use === to avoid surprising results.

When should I use ?? instead of ||?

Use ?? when 0, false or an empty string are valid values you want to keep. || replaces every falsy value, ?? only replaces null and undefined.

What does ?. mean in JavaScript?

It is the optional chaining operator. obj?.prop returns undefined if obj is null or undefined, instead of throwing a TypeError.