πŸŽ“ Velnov

🟨 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.

Key concepts in this topic

ifSyntaxif/elseelse ifChainsif vs else ifOrderLogic bugsOrderingStyleBest practicesTruthinessArraysLogical operatorsswitchcaseFall-throughbreakGrouping casesdefaultStrict equalityFormsTernaryNesting

Jump to: Easy Β· Medium Β· Hard

Easy questions (3)

Q1. easy

Which is the correct if statement syntax?

if (score > 50) {
  console.log("Pass");
}
  1. A if (x > 5) { ... }
  2. B if x > 5: ...
  3. C if x > 5 then ... end
  4. D if [x > 5] { ... }

Answer: A β€” if (x > 5) { ... }

JavaScript requires parentheses around the condition and uses curly braces for the block. (Python uses a colon; other languages use then/end.)

ifSyntax

Q2. easy

When does the else block run?

if (age >= 18) {
  console.log("Adult");
} else {
  console.log("Minor");
}
  1. A Only when the if condition (and every else if) was false
  2. B Always
  3. C Only when the if was true
  4. D Never

Answer: A β€” Only when the if condition (and every else if) was false

else is the catch-all branch; it takes no condition of its own and runs when nothing above it matched.

if/else

Q3. easy

How do you test a second condition when the first fails?

if (s >= 90) grade = "A";
else if (s >= 75) grade = "B";
else if (s >= 60) grade = "C";
else grade = "F";
  1. A else if (condition) { ... }
  2. B elif (condition) { ... }
  3. C elseif condition: ...
  4. D otherwise (condition)

Answer: A β€” else if (condition) { ... }

JavaScript writes it as two words: else if. (elif is Python, elseif is PHP.) You can chain as many as you need.

else ifChains

Medium questions (19)

Q4. medium

What is the output? let x = 7; if (x > 5) console.log("A"); if (x > 6) console.log("B");

  1. A A then B - two independent ifs, both conditions are true
  2. B A only
  3. C B only
  4. 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");

  1. A A only - the chain stops at the first true condition
  2. B A then B
  3. C B only
  4. 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!
  1. A Yes, but it is risky - adding a second line later silently falls outside the if
  2. B No, braces are mandatory
  3. C Only in strict mode
  4. 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");

  1. A no - 0 is falsy
  2. B yes
  3. C 0
  4. 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?

  1. A if (a > 0 && b > 0)
  2. B if (a > 0 and b > 0)
  3. C if (a > 0 AND b > 0)
  4. 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");
}
  1. A Comparing ONE value against several possible cases - a tidy alternative to a long else-if chain
  2. B Looping
  3. C Switching variable types
  4. 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");
}
  1. A Stack several case labels together so they share one block of code
  2. B It can never be useful
  3. C By writing break twice
  4. 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?

  1. A Runs when no case matched - like else
  2. B Runs first
  3. C Runs always
  4. 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"}`);
  1. A const s = age >= 18 ? "adult" : "minor";
  2. B const s = if age >= 18 then "adult" else "minor";
  3. C const s = (age >= 18) ? "adult" | "minor";
  4. 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();
  1. A Calls showDashboard() only if isLoggedIn is truthy - short-circuit evaluation
  2. B Always calls showDashboard()
  3. C Compares the two
  4. 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
  1. A Uses input if it is truthy, otherwise falls back to "Guest"
  2. B Always uses "Guest"
  3. C Compares them
  4. 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
}
  1. A An early return for invalid cases, so the main logic stays unindented
  2. B A security check
  3. C A type of loop
  4. 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?

  1. A if (x >= 10 && x <= 20)
  2. B if (10 <= x <= 20)
  3. C if (x between 10, 20)
  4. 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");

  1. A unset
  2. B set
  3. C undefined
  4. 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)

  1. A if (["apple", "mango", "banana"].includes(fruit))
  2. B if (fruit == "apple" || fruit == "mango" || fruit == "banana")
  3. C if (fruit in "apple mango banana")
  4. 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");

  1. A big
  2. B medium
  3. C small
  4. 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
  1. A Yes - let and const inside { } are not visible outside; var would leak
  2. B No, if blocks never create scope
  3. C Only in strict mode
  4. 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() !== "") { }
  1. A if (input.trim() !== "")
  2. B if (input !== null)
  3. C if (input.length) // fails for " "
  4. 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";
  1. A A switch statement, or an object/map lookup
  2. B Deeply nested ifs
  3. C Many separate if statements
  4. 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";

  1. A The chain matches the FIRST true condition (95 >= 60) - the tests are in the wrong order
  2. B The comparison operators are wrong
  3. C grade is undefined
  4. 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");
  1. A truthy - an empty ARRAY is truthy in JavaScript
  2. B falsy
  3. C Error
  4. 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'
  1. A Execution FALLS THROUGH into the following cases until it hits a break or the end
  2. B SyntaxError
  3. C Only that case runs anyway
  4. 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");
}
  1. A === (strict) - so "5" does NOT match case 5
  2. B == (loose)
  3. C It depends on the browser
  4. 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");

  1. A "a" - the first condition is true so the rest is skipped
  2. B "b"
  3. C "c"
  4. 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");

  1. A A - the STRING "0" is non-empty, therefore truthy
  2. B B
  3. C 0
  4. 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");

  1. A A only - (3>2) becomes true, then true > 1 is false
  2. B A and B
  3. C B only
  4. 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");

  1. A no name - optional chaining returns undefined instead of throwing
  2. B TypeError
  3. C has name
  4. 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

Practice β€œConditionals” as a quiz