JavaScript · Beginner
Conditions in JavaScript: if, else if, else and switch
In short: An if statement runs its block only when the condition is truthy; else if and else supply alternatives, and switch compares one value against several cases with strict equality. JavaScript converts the condition to a boolean, so 0, an empty string, null, undefined and NaN count as false and everything else counts as true.
Choosing what runs
Without conditions a program does the same thing every time. An if statement lets it react to data: the condition in parentheses is evaluated, and the block runs only when the result is truthy. An else block runs when it is not. Chaining else if tests several conditions in order, and the first one that holds wins; the remaining branches are skipped even if their conditions would also be true, so order the tests from most specific to least. Only the block that matches runs, then execution continues after the whole chain.
The condition does not have to be a boolean. JavaScript converts whatever you put there: 0, 0n, "", null, undefined, NaN and false are the falsy values; every other value, including "0", "false", an empty array and an empty object, is truthy. This makes if (name) a compact way to say "a non-empty name was given", and if (!list.length) a way to say "the list is empty". Be deliberate about it: if (count) treats a count of zero as "no count", which is sometimes right and sometimes a bug.
Comparisons inside conditions should use === and !==, and values read from input should be converted before being compared with numbers; the operators lesson explains why. Combine conditions with &&, || and !, and use parentheses when both && and || appear.
switch compares one value against a list of case labels using strict equality and runs the statements from the first matching label onward. Each case normally ends with break; without it, execution falls through into the next case's statements, which is occasionally useful for grouping labels but usually a mistake. The default label catches everything that did not match. switch reads well when one variable is tested against many fixed values, such as a command word or a status code; for ranges and compound tests, an if chain is clearer.
A few habits keep conditional code readable. Return or print early for the simple cases (a "guard clause") instead of nesting the main logic inside several levels of braces. Use the conditional operator a ? b : c when you only need to pick one of two values. And always write the braces, even around a single statement, so that adding a second line later cannot silently fall outside the block.
Syntax
if (condition) {
// runs when condition is truthy
} else if (otherCondition) {
// runs when the first was falsy and this one is truthy
} else {
// runs when none matched
}
switch (value) {
case "a":
case "b": // "a" and "b" share the statements below
statements;
break; // leave the switch
case "c":
statements;
break;
default:
statements; // no case matched
}
const result = condition ? valueIfTrue : valueIfFalse;Conditions are converted to booleans. switch uses === to compare, so the value and the case labels must have the same type.
A library fine with an if chain
The input is the number of days a book is overdue, here 20. The bands are tested in order.
const daysLate = Number(readline());
let fine;
if (daysLate <= 0) {
fine = 0;
} else if (daysLate <= 7) {
fine = daysLate * 0.25;
} else if (daysLate <= 30) {
fine = 7 * 0.25 + (daysLate - 7) * 0.5;
} else {
fine = 15;
}
console.log("Days late:", daysLate);
console.log("Fine:", fine.toFixed(2));
if (fine > 5) {
console.log("Borrowing suspended until paid");
}Input given to the program: 20
Output
Days late: 20 Fine: 8.25 Borrowing suspended until paid
Twenty days fails the first two tests and passes daysLate <= 30, so the third branch runs: seven days at 0.25 plus thirteen at 0.5. Because the earlier branches already handled anything up to 7, the third condition does not need to say daysLate > 7; the order of the chain does that. The separate if at the end has no else, so when the fine is small the program simply prints nothing extra. Try 3, 45 and 0 as input to see the other branches.
Which values are truthy
Each line converts a different value to a boolean by using it as a condition.
const wanted = "";
if (wanted) {
console.log("empty string is truthy");
} else {
console.log("empty string is falsy");
}
console.log(0 ? "0 is truthy" : "0 is falsy");
console.log("0" ? '"0" is truthy' : '"0" is falsy');
console.log(null ? "null is truthy" : "null is falsy");
console.log(NaN ? "NaN is truthy" : "NaN is falsy");
console.log([] ? "[] is truthy" : "[] is falsy");
console.log("false" ? '"false" is truthy' : '"false" is falsy');
const items = [];
if (!items.length) {
console.log("nothing to process");
}Output
empty string is falsy 0 is falsy "0" is truthy null is falsy NaN is falsy [] is truthy "false" is truthy nothing to process
Only the seven falsy values convert to false. The string "0" and the string "false" are non-empty text, so they are truthy, which catches out anyone who reads a yes/no answer from input and tests it directly. An empty array is an object, and every object is truthy, so to test for emptiness you look at .length, as the last lines do. The ternary is used here only to pick which message to print.
switch on a command word
The input line is the command stop. Two labels share one branch, one branch has two statements, and default handles the rest.
const command = readline();
switch (command) {
case "play":
case "resume":
console.log("Playing");
break;
case "pause":
console.log("Paused");
break;
case "stop":
console.log("Stopped");
console.log("Position reset to 0:00");
break;
default:
console.log("Unknown command: " + command);
}
console.log("Ready for the next command");Input given to the program: stop
Output
Stopped Position reset to 0:00 Ready for the next command
command is compared with each label using === until "stop" matches; both statements in that case run, and break jumps to the line after the switch. "play" has no statements and no break of its own, so it deliberately falls through into "resume", which is the idiomatic way to give two labels one branch. Run the program with the input eject and the default branch reports the unknown word.
Common mistakes
Using a single = in a condition
Why it goes wrong:
if (status = "open")assigns the string and then tests it; a non-empty string is truthy, so the block always runs andstatushas been overwritten.Fix: Compare with
===. Some people write the constant first ("open" === status) so a typo becomes a syntax error.JavaScript · fixif (status === "open") { console.log("door is open"); }Forgetting break in a switch
Why it goes wrong: Without
break, execution continues into the next case's statements, so a"pause"command would also print the stop messages.Fix: End every case with
break(orreturninside a function), and leave it out only when two labels are meant to share a branch and a comment says so.Comparing input text with a number
Why it goes wrong:
readline()returns a string, soif (answer === 5)is never true even when the user typed 5, andswitch (answer)withcase 5:never matches.Fix: Convert first:
const answer = Number(readline());, or compare with the string"5"if you really want text.Writing a range test the way it is written in mathematics
Why it goes wrong:
if (1 < x < 10)evaluates1 < xfirst, giving true or false, then compares that boolean (converted to 1 or 0) with 10, which is always true.Fix: Join two comparisons with
&&.JavaScript · fixif (x > 1 && x < 10) { console.log("in range"); }
Where you use this
Validating input is the everyday use. A program reads a value, checks it, and either reports a problem or carries on; writing the checks as guard clauses at the top keeps the real work unindented and easy to follow. Classification is the other: turning a score into a grade, a temperature into a warning level, or a status code into a message is an if chain ordered from the strictest band to the loosest, or a switch when the input is one of a fixed set of words. Notice how the snippet handles the invalid case first and only then computes.
const raw = readline();
const score = Number(raw);
if (raw === "" || Number.isNaN(score)) {
console.log("not a number");
} else if (score < 0 || score > 100) {
console.log("out of range");
} else {
console.log(score >= 50 ? "pass" : "fail");
}Key points
ifruns its block when the condition is truthy;else ifandelsegive alternatives, and only the first matching branch runs.- Falsy values:
0,0n,"",null,undefined,NaN,false. Everything else, including"0"and[], is truthy. - Compare with
===; convert input to a number before comparing it with numbers. switchuses strict equality and needsbreakat the end of each case.- Combine range tests with
&&;1 < x < 10does not mean what it looks like. - Always write braces, and handle the simple or invalid cases first.
Try it yourself
Extend the chain so the program prints freezing below 0, cold below 15, mild below 25 and hot otherwise. The input is a temperature in degrees.
const temp = Number(readline());
if (temp < 0) {
console.log("freezing");
}
// add the cold, mild and hot branches
18mildconst temp = Number(readline());
if (temp < 0) {
console.log("freezing");
} else if (temp < 15) {
console.log("cold");
} else if (temp < 25) {
console.log("mild");
} else {
console.log("hot");
}
Practise this
Open the JavaScript playground
Related lessons
- JavaScript Operators: Arithmetic, Comparison and LogicJavaScript's arithmetic, assignment, comparison and logical operators, why === beats ==, how + behaves with strings, and what ?? and the ternary do.9 min
- Loops in JavaScript: for, while, for...of and for...infor, while, do...while, for...of and for...in loops in JavaScript, with break and continue, and how to read every line of input in a loop.9 min
- JavaScript Data Types: Primitives, Objects and typeofThe seven primitive types in JavaScript plus objects, what typeof reports, how numbers behave, and how to convert between strings, numbers and booleans.9 min
Frequently asked questions
When should I use switch instead of if-else in JavaScript?
Use switch when one value is compared against several fixed alternatives, such as a command word, a day name or a status code; the labels read like a table. Use an if chain for ranges (score >= 90), for tests that involve more than one variable, or for conditions that are not simple equality. Both compile to the same kind of branching, so the choice is about readability.
Does switch use == or === to compare?
Strict equality, ===. A switch on the string "5" will not match case 5: and a switch on a number will not match a string label. Convert the value before the switch if the types could differ.
Can I write an if statement without braces?
Yes, a single statement may follow the condition directly: if (x > 0) console.log(x);. It is legal but fragile, because a second line added under it will look indented into the block while actually running unconditionally. Most style guides require the braces for that reason.
How this page was checked. Every program on it was run with Node.js 22 at build time; runs in your browser in an isolated Web Worker by the publishing checks, and the output shown is what it printed. The Run buttons execute the same code on your device; nothing you type is sent anywhere.