π¨ JavaScript Β· Topic 6 of 20
Conditionals β JavaScript Questions with Answers
30 practice questions on Conditionals, each with the correct answer and a clear explanation of why it is right. Read through them as revision notes, or take this topic as an interactive quiz to test yourself.
3 easy Β· 19 medium Β· 8 hard Β· Part of JavaScript: The language of the web - basics to advanced, 20 topics.
Medium questions (19)
Q4. medium
What is the output?
let x = 7;
if (x > 5) console.log("A");
if (x > 6) console.log("B");
- A A then B - two independent ifs, both conditions are true
- B A only
- C B only
- D Nothing
Answer: A β A then B - two independent ifs, both conditions are true
Separate if statements are each evaluated. With 'else if' instead, only the first matching branch would run.
if vs else if
Q5. medium
What is the output?
let x = 7;
if (x > 5) console.log("A");
else if (x > 6) console.log("B");
- A A only - the chain stops at the first true condition
- B A then B
- C B only
- D Nothing
Answer: A β A only - the chain stops at the first true condition
In an if/else-if chain, evaluation stops at the first true branch. The x > 6 test never runs, even though it is also true. Order matters: put the most specific condition first.
else ifOrder
Q7. medium
Can you omit the curly braces for a single statement?
if (x) console.log("hi");
if (x)
doA();
doB(); // ALWAYS runs - not part of the if!
- A Yes, but it is risky - adding a second line later silently falls outside the if
- B No, braces are mandatory
- C Only in strict mode
- D Only for else
Answer: A β Yes, but it is risky - adding a second line later silently falls outside the if
Braceless ifs are legal but a known source of bugs (the famous 'goto fail' security flaw). Most style guides require braces always.
StyleBest practices
Q8. medium
What is the output?
if (0) console.log("yes");
else console.log("no");
- A no - 0 is falsy
- B yes
- C 0
- D Error
Answer: A β no - 0 is falsy
if converts the condition to a boolean. 0 is one of the falsy values (false, 0, "", null, undefined, NaN), so the else branch runs.
Truthiness
Q10. medium
How do you require BOTH conditions to be true?
- A if (a > 0 && b > 0)
- B if (a > 0 and b > 0)
- C if (a > 0 AND b > 0)
- D if (a > 0, b > 0)
Answer: A β if (a > 0 && b > 0)
JavaScript uses the symbols && (AND), || (OR) and ! (NOT) - not the words. (Python uses the words.)
Logical operators
Q11. medium
What is the switch statement used for?
switch (day) {
case "Mon": console.log("Start"); break;
case "Fri": console.log("Almost!"); break;
default: console.log("Midweek");
}
- A Comparing ONE value against several possible cases - a tidy alternative to a long else-if chain
- B Looping
- C Switching variable types
- D Error handling
Answer: A β Comparing ONE value against several possible cases - a tidy alternative to a long else-if chain
switch compares the expression to each case using strict equality (===) and runs the matching block.
switchcase
Q13. medium
How can fall-through be used INTENTIONALLY?
switch (day) {
case "Sat":
case "Sun":
console.log("Weekend");
break;
default:
console.log("Weekday");
}
- A Stack several case labels together so they share one block of code
- B It can never be useful
- C By writing break twice
- D By using continue
Answer: A β Stack several case labels together so they share one block of code
Empty cases stacked above a shared body let several values run the same code - the one legitimate use of fall-through.
switchGrouping cases
Q14. medium
What does the default clause in a switch do?
- A Runs when no case matched - like else
- B Runs first
- C Runs always
- D Is required
Answer: A β Runs when no case matched - like else
default is optional and handles unmatched values. By convention it goes last (though technically it can appear anywhere).
switchdefault
Q16. medium
What is the ternary equivalent of this?
if (age >= 18) s = "adult"; else s = "minor";
console.log(`You are ${age >= 18 ? "adult" : "minor"}`);
- A const s = age >= 18 ? "adult" : "minor";
- B const s = if age >= 18 then "adult" else "minor";
- C const s = (age >= 18) ? "adult" | "minor";
- D const s = age >= 18 : "adult" ? "minor";
Answer: A β const s = age >= 18 ? "adult" : "minor";
condition ? valueIfTrue : valueIfFalse. It is an expression, so it can be assigned, returned, or embedded in a template literal.
Ternary
Q18. medium
What does this pattern do?
isLoggedIn && showDashboard();
// equivalent to:
if (isLoggedIn) showDashboard();
- A Calls showDashboard() only if isLoggedIn is truthy - short-circuit evaluation
- B Always calls showDashboard()
- C Compares the two
- D SyntaxError
Answer: A β Calls showDashboard() only if isLoggedIn is truthy - short-circuit evaluation
&& stops at the first falsy operand, so the right side runs only when the left is truthy. Common in React JSX for conditional rendering.
Short-circuitGuard clause
Q19. medium
What does this do?
const name = input || "Guest";
const count = 0;
console.log(count || 10); // 10 - probably wrong
console.log(count ?? 10); // 0 - correct
- A Uses input if it is truthy, otherwise falls back to "Guest"
- B Always uses "Guest"
- C Compares them
- D Concatenates them
Answer: A β Uses input if it is truthy, otherwise falls back to "Guest"
|| returns the first truthy operand. Careful: it also replaces valid values like 0 and "" - use ?? if only null/undefined should trigger the fallback.
DefaultsNullish coalescing
Q20. medium
What is a guard clause?
function process(user) {
if (!user) return; // guard
if (!user.active) return; // guard
// main logic, not nested
}
- A An early return for invalid cases, so the main logic stays unindented
- B A security check
- C A type of loop
- D A try/catch block
Answer: A β An early return for invalid cases, so the main logic stays unindented
Handling the exceptional cases first and returning early avoids deep nesting and keeps the 'happy path' readable.
Early returnReadability
Q22. medium
How do you check that a value is between 10 and 20 inclusive?
- A if (x >= 10 && x <= 20)
- B if (10 <= x <= 20)
- C if (x between 10, 20)
- D if (x in [10, 20])
Answer: A β if (x >= 10 && x <= 20)
Chained comparisons do not work in JavaScript: 10 <= x <= 20 evaluates left to right into a boolean, then compares that boolean to 20 - always true. Combine with &&.
Chained comparisonLogical AND
Q23. medium
What is the output?
let x;
if (x === undefined) console.log("unset");
else console.log("set");
- A unset
- B set
- C undefined
- D Error
Answer: A β unset
A declared but unassigned variable holds undefined, so the strict comparison succeeds. Alternatively 'if (x == null)' catches both undefined and null.
undefinedChecks
Q25. medium
Which is the cleanest way to check several possible values?
if (fruit is apple, mango or banana)
- A if (["apple", "mango", "banana"].includes(fruit))
- B if (fruit == "apple" || fruit == "mango" || fruit == "banana")
- C if (fruit in "apple mango banana")
- D if (fruit === ["apple", "mango"])
Answer: A β if (["apple", "mango", "banana"].includes(fruit))
includes() on an array is readable and easy to extend. Option B works but grows unwieldy; option D compares against an array object and is always false.
includesReadability
Q26. medium
What is the output?
const x = 5;
console.log(x > 3 ? x > 4 ? "big" : "medium" : "small");
- A big
- B medium
- C small
- D SyntaxError
Answer: A β big
x > 3 is true, so evaluate the nested ternary: x > 4 is also true, giving "big". Correct, but this is exactly the nesting that hurts readability.
Nested ternary
Q27. medium
Does an if block create a new scope for let/const?
if (true) {
let a = 1;
var b = 2;
}
// console.log(a); // ReferenceError
console.log(b); // 2 - leaked
- A Yes - let and const inside { } are not visible outside; var would leak
- B No, if blocks never create scope
- C Only in strict mode
- D Only for const
Answer: A β Yes - let and const inside { } are not visible outside; var would leak
Curly braces form a block scope for let/const. var ignores blocks and belongs to the enclosing function - one of the main reasons to avoid var.
Block scopevar vs let
Q29. medium
Which condition correctly checks that a string is non-empty after trimming?
if (nameInput.value.trim() !== "") { }
- A if (input.trim() !== "")
- B if (input !== null)
- C if (input.length) // fails for " "
- D if (input)
Answer: A β if (input.trim() !== "")
A string of only spaces is truthy and has length > 0, so options C and D wrongly accept it. Trim first, then compare - standard form validation.
Validationtrim
Q30. medium
What is the recommended way to write a long chain of conditions on ONE variable?
const messages = { 404: "Not found", 500: "Server error" };
const msg = messages[code] ?? "Unknown";
- A A switch statement, or an object/map lookup
- B Deeply nested ifs
- C Many separate if statements
- D A while loop
Answer: A β A switch statement, or an object/map lookup
switch reads better than a long else-if chain. For simple value-to-value mappings, an object lookup is even cleaner and easier to extend.
switchLookup tables
Hard questions (8)
Q6. hard
Why does this print "C" for score = 95?
if (s >= 60) grade = "C";
else if (s >= 75) grade = "B";
else if (s >= 90) grade = "A";
- A The chain matches the FIRST true condition (95 >= 60) - the tests are in the wrong order
- B The comparison operators are wrong
- C grade is undefined
- D It should print A
Answer: A β The chain matches the FIRST true condition (95 >= 60) - the tests are in the wrong order
With overlapping ranges, always test the most restrictive first: >= 90, then >= 75, then >= 60. This ordering bug is extremely common in grading code.
Logic bugsOrdering
Q9. hard
What is the output?
const arr = [];
if (arr) console.log("truthy");
else console.log("falsy");
if (arr.length === 0) console.log("empty");
- A truthy - an empty ARRAY is truthy in JavaScript
- B falsy
- C Error
- D undefined
Answer: A β truthy - an empty ARRAY is truthy in JavaScript
All objects, including empty arrays and objects, are truthy. To test emptiness use arr.length === 0. (In Python [] is falsy - a common cross-language mix-up.)
TruthinessArrays
Q12. hard
What happens if you forget break in a switch case?
switch (x) {
case 1:
console.log("one"); // no break - falls through!
case 2:
console.log("two");
break;
}
// x = 1 prints BOTH 'one' and 'two'
- A Execution FALLS THROUGH into the following cases until it hits a break or the end
- B SyntaxError
- C Only that case runs anyway
- D The switch is skipped
Answer: A β Execution FALLS THROUGH into the following cases until it hits a break or the end
Without break, JavaScript continues executing subsequent case bodies regardless of their labels. This causes real bugs - but is occasionally used deliberately to group cases.
Fall-throughbreak
Q15. hard
Does switch use == or === for matching?
const val = "5"; // from a form
switch (Number(val)) { // convert first!
case 5: console.log("five");
}
- A === (strict) - so "5" does NOT match case 5
- B == (loose)
- C It depends on the browser
- D It uses Object.is
Answer: A β === (strict) - so "5" does NOT match case 5
switch uses strict comparison. A value read from an input field (a string) will not match a numeric case - convert it first with Number().
Strict equalityForms
Q17. hard
What is the output?
console.log(true ? "a" : false ? "b" : "c");
- A "a" - the first condition is true so the rest is skipped
- B "b"
- C "c"
- D SyntaxError
Answer: A β "a" - the first condition is true so the rest is skipped
Nested ternaries evaluate left to right; the true branch returns "a" immediately. Nesting more than one level hurts readability - prefer if/else there.
TernaryNesting
Q21. hard
What is the output?
if ("0") console.log("A");
else console.log("B");
- A A - the STRING "0" is non-empty, therefore truthy
- B B
- C 0
- D Error
Answer: A β A - the STRING "0" is non-empty, therefore truthy
Only the empty string is falsy; "0" and "false" are truthy strings. Values arriving from APIs, forms or localStorage are strings - compare explicitly rather than relying on truthiness.
TruthinessGotchas
Q24. hard
What is the output?
if (1 < 2 < 3) console.log("A");
if (3 > 2 > 1) console.log("B");
- A A only - (3>2) becomes true, then true > 1 is false
- B A and B
- C B only
- D Neither
Answer: A β A only - (3>2) becomes true, then true > 1 is false
1 < 2 gives true, and true < 3 converts true to 1, so 1 < 3 is true (prints A). But 3 > 2 gives true, and true > 1 is 1 > 1 which is false (no B). Never chain comparisons.
CoercionComparison chains
Q28. hard
What is the output?
const v = null;
if (v?.name) console.log("has name");
else console.log("no name");
- A no name - optional chaining returns undefined instead of throwing
- B TypeError
- C has name
- D null
Answer: A β no name - optional chaining returns undefined instead of throwing
Without ?., reading v.name on null throws 'Cannot read properties of null'. Optional chaining short-circuits to undefined, which is falsy, so else runs.
Optional chainingNull safety