Operators and conditionals
โ Report an issue with this lessonif (age >= 18) {
console.log("Adult");
} else if (age >= 13) {
console.log("Teenager");
} else {
console.log("Child");
}
Use === and !== (strict equality), not
==/!=. The strict versions don't silently convert
types, which avoids a whole category of confusing bugs:
0 == false // true -- surprising
0 === false // false -- correct, different types
The ternary operator is a compact if/else for simple cases:
const status = age >= 18 ? "adult" : "minor";
Truthy and falsy values
An if condition doesn't have to be a strict boolean --
JavaScript converts whatever you give it to true or
false. Only a handful of values are "falsy":
false, 0, "" (empty string),
null, undefined, and NaN. Everything
else -- including "0" as a string, and any non-empty string or
object -- is truthy:
if ("") {
console.log("won't run -- empty string is falsy");
}
if ("0") {
console.log("this runs -- non-empty string is truthy, even '0'");
}
if ([]) {
console.log("this runs too -- even an empty array is truthy");
}
This is why you'll often see a simple existence check written as
if (user) { ... } rather than
if (user !== null && user !== undefined) { ... }.
Short-circuiting with && and ||
const name = userName || "Guest"; // fallback if userName is falsy
isLoggedIn && console.log("Welcome back"); // only runs if isLoggedIn is truthy
|| returns its first truthy value, which makes it a common
(if slightly old-fashioned) way to supply a default. Newer code often uses
?? (nullish coalescing) instead, which only falls back on
null/undefined rather than every falsy value --
important if 0 or "" are valid values you don't
want overridden:
const count = quantity ?? 1; // only falls back if quantity is null/undefined
// with ||, a quantity of 0 would incorrectly fall back to 1
switch: an alternative to long if/elif chains
switch (status) {
case "active":
console.log("Account is active");
break;
case "suspended":
console.log("Account is suspended");
break;
default:
console.log("Unknown status");
}
Each case needs its own break, or execution
"falls through" into the next case -- usually not what you want, and a
common source of bugs when a break gets forgotten.
Try it yourself
Adult
Run your code and get it working before marking this lesson complete.
8 more lessons โ including Project: build a simple calculator โ plus a certificate are waiting.
Unlock the full course โ $29.99