JavaScript Tutorial · JavaScript Basics · Lesson 11 of 44
JavaScript Operators
Arithmetic, assignment, comparison, logical and nullish operators.
Arithmetic and assignment
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.
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 ?? breturnsbonly whenaisnullorundefined— safer than||for defaults.obj?.propreturnsundefinedinstead of throwing whenobjis null or undefined.
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:
const age = 16;
const status = age >= 18 ? "adult" : "minor";
console.log(status);
Output
minor
Test yourself
What does 0 ?? 10 evaluate to?
010nullundefined
Show answer
Answer: 0
?? only falls back when the left side is null or undefined; 0 is kept.