Quick Overview
`if` branches on truthiness rather than equality, so `0`, `""`, `null` and `undefined` all take the else path. A ternary evaluates to a value, where `if` only performs a statement.
Conditionals allow your application to make decisions at runtime, executing specific code blocks based on user permissions, state, or input values.
Clean conditional branching prevents nested callback spaghetti and makes business logic obvious and maintainable.
Standard conditional branching uses if, else if, and else:
const userRole = "editor";
if (userRole === "admin") {
console.log("Full control access granted.");
} else if (userRole === "editor") {
console.log("Content editing access granted.");
} else {
console.log("Read-only access granted.");
}
For quick two-way assignments or inline return expressions, use the ternary operator (condition ? exprIfTrue : exprIfFalse):
const age = 20;
// Standard if/else assignment (Verbose)
let statusMessage;
if (age >= 18) {
statusMessage = "Adult";
} else {
statusMessage = "Minor";
}
// Equivalent Ternary Assignment (Concise 1-liner!)
const status = age >= 18 ? "Adult" : "Minor";
console.log(status); // "Adult"
Combine conditions using logical operators:
&& (AND): Both conditions must be truthy.|| (OR): At least one condition must be truthy.?? (Nullish Coalescing): Provides a fallback value ONLY if the left side is null or undefined (unlike ||, which triggers on all falsy values like 0 or "").const userCount = 0;
const countOrFallback1 = userCount || 10; // Returns 10 (because 0 is falsy!)
const countOrFallback2 = userCount ?? 10; // Returns 0 (because 0 is NOT nullish!)
a ? b : c ? d : e) makes code impossible to read. Use if/else or a switch statement when handling 3+ branches.|| with ??: Using || for default values can accidentally overwrite valid falsy inputs like 0 or false. Use ?? when 0 or false are valid values!Write it yourself. The tests below run against your code.
Use ternaries for simple assignments and if/else for multi-step logic. Next, let's solve the confusion between undefined and not defined!
Primitives copy by value and objects copy by reference, so `b = a` duplicates a number but shares an object. That single distinction explains most surprise mutations in a codebase.
`const` prevents reassignment, not mutation: a `const` object's properties can still be changed. `let` is scoped to its block, while `var` is function-scoped and leaks out of loops.
Only backticks interpolate: `${user}` reads the variable, while the identical text in quotes prints literally. Strings are immutable, so every method returns a new one rather than editing in place.