JS If Else
JavaScript's branching primitives are if, else if, else, the ternary ?:, and short-circuit logical operators. They cover everything from a one-line guard to a multi-case decision tree.
The basics
JS
if (xp >= 1000) {
console.log("Ninja");
} else if (xp >= 500) {
console.log("Coder");
} else {
console.log("Newcomer");
}
Ternary for assignments
JS
const label = xp >= 500 ? "Coder" : "Newcomer"; const price = user.member ? base * 0.8 : base;
Short-circuit operators
| Operator | Returns | Example |
|---|---|---|
&& | First falsy, else last value. | isOpen && close() — only calls if isOpen |
|| | First truthy, else last. | name || "Anonymous" — fallback |
?? | Right side only if left is null or undefined. | count ?? 0 — doesn't override 0 or "" |
?. | Safe navigation. | user?.address?.city — undefined if anything in the chain is nullish |
Falsy values to remember
In a boolean context, these all evaluate to false:
false0and-0""(empty string)nullundefinedNaN
Everything else — including "0", "false", [], {} — is truthy.
Tip: Prefer
?? over || when a real 0 or empty string is a valid value: count ?? 0 keeps a 0 instead of replacing it.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS If Else!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Use the operator that defaults to 0 only when count is null or undefined (preserving a real 0).
const n = count
0;
Two question marks.
Discussion
Loading…