JavaScript Conditionals in Depth
Go beyond basic if statements: master comparison operators, ===, logical AND/OR/NOT, else if chains, truthy and falsy values, the ternary operator and switch. Runnable code, a worked example and a quiz.
Key takeaways
- === compares value AND type without surprises; prefer it over ==
- && (and), || (or) and ! (not) combine and flip conditions
- else if chains test several cases in order; the first true one wins
- Every value is truthy or falsy β 0, '', null, undefined and NaN are falsy
- The ternary ?: is a compact if/else, and switch handles many fixed cases cleanly
Decisions, done properly
You've met the basic if statement in Making Decisions with If. This lesson goes deeper into how JavaScript actually decides things: the comparison operators, combining conditions with logic, the difference between truthy and falsy values, and the two compact alternatives to if β the ternary operator and switch. Get these right and your programs become far more precise.
Comparison operators
A condition is just an expression that evaluates to true or false. These operators produce booleans:
| Operator | Means | Example (true) |
|---|---|---|
=== | equal (value and type) | 5 === 5 |
!== | not equal | 5 !== 6 |
> < | greater / less than | 7 > 3 |
>= <= | greater/less or equal | 4 >= 4 |
Why === and not ==
JavaScript has two equality operators, and the difference matters. == (loose equality) converts the two sides to the same type before comparing, which leads to surprises:
console.log(5 == "5"); // true β string "5" is converted to a number
console.log(5 === "5"); // false β different types, no conversion
console.log(0 == ""); // true β surprising!
console.log(0 === ""); // false β clear and correct
=== (strict equality) compares value and type with no hidden conversion. The rule for clean code is simple: always use === and !== unless you have a very specific reason not to.
Combining conditions with logic
Three logical operators let you build complex conditions:
&&(AND) β true only if both sides are true.||(OR) β true if at least one side is true.!(NOT) β flips true to false and back.
let age = 16;
let hasTicket = true;
if (age >= 12 && hasTicket) {
console.log("Enjoy the film!");
}
if (age < 12 || !hasTicket) {
console.log("Sorry, you can't enter.");
}
Read age >= 12 && hasTicket as "twelve or older AND holds a ticket." Parentheses help when you mix operators: (a || b) && c.
else if chains
When there are several possibilities, chain them. JavaScript checks each condition top to bottom and runs the block for the first one that's true, then skips the rest:
let score = 84;
let grade;
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else if (score >= 70) {
grade = "C";
} else {
grade = "F";
}
console.log(grade); // "B"
Order matters: because 84 passes the >= 80 test, it never reaches >= 70. The final else catches everything left over.
Truthy and falsy
In a condition, JavaScript treats every value as either truthy or falsy. There are only a handful of falsy values:
false 0 "" null undefined NaN
Everything else is truthy β including "0", "false", [] and {}. This lets you check for "is there a value here at all?" concisely:
let name = "";
if (name) {
console.log("Hi " + name);
} else {
console.log("No name given"); // runs, because "" is falsy
}
You can also use || to supply a default: let display = name || "Guest"; gives "Guest" whenever name is empty.
The ternary operator
For a simple either/or choice, the ternary operator condition ? valueIfTrue : valueIfFalse is a one-line if/else:
let age = 15;
let category = age >= 13 ? "teen" : "child";
console.log(category); // "teen"
It's perfect for assigning a value based on a condition. Avoid nesting ternaries deeply β they get hard to read.
switch for fixed cases
When you compare one variable against many fixed values, switch is cleaner than a long else if chain:
let day = "Sat";
let plan;
switch (day) {
case "Sat":
case "Sun":
plan = "Relax";
break;
default:
plan = "Work";
}
console.log(plan); // "Relax"
Each case is checked with ===. The break stops execution falling through into the next case β forgetting it is a classic bug. Stacking case "Sat": and case "Sun": lets both share the same code. default handles anything unmatched.
A complete worked example
Save this as a .js file and run it with Node, or paste it into your browser console. It classifies the weather into advice.
function adviceFor(tempC, isRaining) {
// Strict comparisons, combined logic, an else-if chain, and a ternary
if (isRaining && tempC < 10) {
return "Cold and wet β coat and umbrella! βπ§₯";
} else if (tempC >= 25) {
return "Hot β sunscreen and water. βοΈ";
} else if (tempC >= 15) {
return "Mild β a light jacket is plenty. π";
} else {
return "Chilly β wrap up warm. π§£";
}
}
console.log(adviceFor(8, true)); // Cold and wet...
console.log(adviceFor(28, false)); // Hot...
console.log(adviceFor(18, false)); // Mild...
// A quick ternary for a yes/no message
let tempC = 30;
let alert = tempC > 27 ? "Heat warning!" : "Temperature normal.";
console.log(alert); // Heat warning!
Reading the result: the function uses && to combine two facts, an else if chain to grade the temperature in order (highest first), and a final else as the catch-all. The separate ternary shows the compact form for a single decision.
Try it yourself
- Add a windy case. Give
adviceFora third parameterwindy, and when it's true and the temperature is below 15, return a "windy and cold" message. Place it carefully in the chain so the order stays correct. - Prove the falsy list. Loop over
[0, "", "hi", null, 42, NaN]and print whether each is truthy or falsy using a ternary. (You'll need a loop β see JavaScript Loops and Arrays.) - Rewrite with switch. Turn a small grade function into a
switchon a letter and print a message for each grade, remembering yourbreakstatements.
Challenge: Build a tiny "rock, paper, scissors" judge. Write a function winner(a, b) that takes two moves and returns "draw", "a" or "b". Use a clean combination of comparisons and logical operators β and try writing the win conditions with a switch to see which reads better.
Quick quiz
Test yourself and earn XP
Why prefer === over == in JavaScript?
=== checks both value and type, so '5' === 5 is false. == converts types first and causes surprises.
What does the && operator require?
&& (logical AND) is only true when BOTH conditions are true.
Which of these is a falsy value?
0 is falsy, along with '', null, undefined, NaN and false.
What does age >= 13 ? 'teen' : 'child' return when age is 10?
The ternary returns the value after ? when true, after : when false. 10 >= 13 is false, so 'child'.
In an else if chain, how many blocks run?
JavaScript runs the block for the first condition that is true, then skips the rest of the chain.
FAQ
Use switch when you're comparing one variable against many fixed, known values β like a day name, a menu choice, or a status code. It reads more cleanly than a long else-if chain. Use else if when your conditions are ranges or involve different variables and operators, like 'score >= 90' then 'score >= 80'.
JavaScript stops evaluating as soon as the answer is certain. With &&, if the left side is falsy it returns that and never checks the right. With ||, if the left side is truthy it returns that immediately. This is handy for defaults: 'name || "Guest"' gives 'Guest' only when name is empty or missing.
Keep exploring
More in Coding