JavaScript Tutorial · JavaScript Basics · Lesson 11 of 44

JavaScript Operators

Arithmetic, assignment, comparison, logical and nullish operators.

Arithmetic and assignment

Example 1Try it yourself
let count = 10;
count += 5;
count -= 3;
count *= 2;
count++;
console.log(count);
console.log(17 % 5);
console.log("2" + 2, "2" * 2);

Output

25
2
22 4

Comparison: always use ===

=== (strict equality) compares value and type. == converts types first, which gives surprising results. Use === and !== everywhere.

Example 2Try it yourself
console.log(5 === 5);
console.log(5 === "5");
console.log(5 == "5");
console.log(0 == "");
console.log(null == undefined, null === undefined);
console.log(3 !== 4);

Output

true
false
true
true
true false
true

Logical operators

&& (and), || (or) and ! (not). && and || return one of their operands, which makes them handy for defaults — but || treats 0 and "" as missing.

Nullish coalescing and optional chaining

  • a ?? b returns b only when a is null or undefined — safer than || for defaults.
  • obj?.prop returns undefined instead of throwing when obj is null or undefined.
Example 3Try it yourself
const settings = { volume: 0, user: null };
console.log(settings.volume || 50);  // 0 is falsy, so we lose it
console.log(settings.volume ?? 50);  // keeps 0
console.log(settings.user?.name);
console.log(settings.user?.name ?? "Guest");

Output

50
0
undefined
Guest

The ternary operator

condition ? valueIfTrue : valueIfFalse is a compact if/else expression:

Example 4Try it yourself
const age = 16;
const status = age >= 18 ? "adult" : "minor";
console.log(status);

Output

minor

Test yourself

What does 0 ?? 10 evaluate to?

  1. 0
  2. 10
  3. null
  4. undefined
Show answer

Answer: 0

?? only falls back when the left side is null or undefined; 0 is kept.