Episode 1 — Fundamentals / 1.19 — Conditionals and Loops

1.19 -- Exercise Questions: Conditionals and Loops

Practice questions for all six subtopics in Section 1.19. Mix of short-answer, prediction, code-tracing, and mini-script tasks.

How to use this material (instructions)

  1. Read lessons in order -- README.md, then 1.19.a through 1.19.f.
  2. Answer closed-book first -- then compare to the matching lesson.
  3. Use DevTools Console -- paste code snippets and verify your predictions.
  4. Interview prep -- 1.19-Interview-Questions.md.
  5. Quick review -- 1.19-Quick-Revision.md.

1.19.a -- If / Else If / Else (Q1--Q10)

Q1. What value does JavaScript treat the empty string "" as inside an if condition? What about " " (a string with one space)?

Q2. What is wrong with this code? What does it actually do?

let x = 5;
if (x = 10) {
  console.log("ten");
}

Q3. Rewrite the following nested if using guard clauses and early returns:

function process(user) {
  if (user) {
    if (user.isActive) {
      if (user.age >= 18) {
        return "Allowed";
      } else {
        return "Too young";
      }
    } else {
      return "Inactive";
    }
  } else {
    return "No user";
  }
}

Q4. What is the output?

const a = 0;
const b = "";
const c = null;
const d = "hello";

if (a) console.log("a");
if (b) console.log("b");
if (c) console.log("c");
if (d) console.log("d");

Q5. Write a ternary expression that assigns "even" to result if num is even, "odd" otherwise.

Q6. Why is the following nested ternary considered bad practice?

const label = x > 0 ? "positive" : x < 0 ? "negative" : "zero";

Q7. In an else if chain, does JavaScript evaluate all conditions or stop at the first truthy one?

Q8. What is a guard clause? Write one that throws an error if email is an empty string.

Q9. True or false: if ([] && {}) will enter the if block. Explain.

Q10. Write an if-else if-else that classifies a temperature: below 0 is "freezing", 0--15 is "cold", 16--25 is "comfortable", above 25 is "hot".


1.19.b -- Switch Statement (Q11--Q20)

Q11. What type of equality does switch use -- == or ===?

Q12. What is the output of this code?

switch ("2") {
  case 2:
    console.log("number two");
    break;
  case "2":
    console.log("string two");
    break;
}

Q13. What happens if you forget break in a case that matches? Demonstrate with a code example.

Q14. Write a switch statement that maps month numbers (1--12) to season names (Spring, Summer, Autumn, Winter). Group months appropriately.

Q15. Can default appear in the middle of a switch? Does position affect when it runs?

Q16. Rewrite this if-else chain as a switch:

if (dir === "north") y--;
else if (dir === "south") y++;
else if (dir === "east") x++;
else if (dir === "west") x--;
else console.log("Invalid direction");

Q17. Explain the switch (true) pattern. When would you use it?

Q18. What error do you get if you declare const x = 1; inside one case and const x = 2; inside another without braces?

Q19. Write a function using switch that returns the HTTP method description: GET="Retrieve", POST="Create", PUT="Update", DELETE="Remove", anything else="Unknown".

Q20. When would you prefer if-else over switch? Give two specific scenarios.


1.19.c -- For Loop (Q21--Q32)

Q21. Label the three parts of for (let i = 0; i < 10; i += 2) and state when each runs.

Q22. What is the output?

for (let i = 5; i > 0; i--) {
  console.log(i);
}

Q23. Write a for loop that iterates over ["a", "b", "c"] and prints each element with its index.

Q24. Rewrite Q23 using for...of with .entries().

Q25. Why should you not use for...in on arrays? Demonstrate the problem.

Q26. What is the output?

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0);
}

Q27. Fix Q26 using let.

Q28. Write nested for loops to print all pairs (i, j) where i and j each go from 1 to 3.

Q29. What is the time complexity of the nested loop in Q28 in Big-O notation?

Q30. Are all three parts of the for header required? What happens if you write for (;;) {}?

Q31. Write a for...in loop that prints all own properties of { name: "Alice", age: 30, city: "NYC" }.

Q32. What is the output?

const str = "Hello";
for (const ch of str) {
  if (ch === "l") continue;
  process.stdout.write(ch);
}

1.19.d -- While and Do-While (Q33--Q42)

Q33. What is the fundamental difference between while and do...while?

Q34. What is the output?

let n = 5;
while (n > 5) {
  console.log(n);
  n--;
}
console.log("done");

Q35. What is the output?

let n = 5;
do {
  console.log(n);
  n--;
} while (n > 5);
console.log("done");

Q36. Convert the following for loop to a while loop:

for (let i = 10; i >= 0; i -= 2) {
  console.log(i);
}

Q37. Write a while loop that sums all numbers from 1 to 100.

Q38. What makes the following an infinite loop? How would you fix it?

let x = 1;
while (x !== 10) {
  console.log(x);
  x += 3;
}

Q39. Write a do...while loop that simulates asking for user input until a valid number (1--5) is entered. (Use a hardcoded array of inputs for testing.)

Q40. Explain what a sentinel value is. Give an example of a sentinel-controlled loop.

Q41. Is the semicolon at the end of do { } while (cond); required?

Q42. Write a while loop that extracts and prints each digit of the number 9876 (from right to left).


1.19.e -- Break and Continue (Q43--Q52)

Q43. What is the output?

for (let i = 0; i < 5; i++) {
  if (i === 3) break;
  console.log(i);
}

Q44. What is the output?

for (let i = 0; i < 5; i++) {
  if (i === 3) continue;
  console.log(i);
}

Q45. In a nested loop, does break exit all loops or just the innermost?

Q46. Write a labeled loop that searches a 2D array for the value 42 and breaks out of both loops when found.

Q47. What is the difference between break and return inside a loop within a function?

Q48. Why can continue cause an infinite loop in a while loop? Show the bug and the fix.

Q49. What is the output?

for (let i = 0; i < 3; i++) {
  switch (i) {
    case 1:
      break;  // Does this break the for loop?
  }
  console.log(i);
}

Q50. Write a loop that iterates through an array of numbers and uses continue to skip negative numbers, computing the sum of only positive values.

Q51. Rewrite the following using break with a label:

let found = false;
for (let i = 0; i < rows.length; i++) {
  for (let j = 0; j < rows[i].length; j++) {
    if (rows[i][j] === target) {
      found = true;
      break;
    }
  }
  if (found) break;
}

Q52. When does using continue hurt readability? Give an example of a better alternative.


Mixed / Comprehensive (Q53--Q58)

Q53. Write a function countVowels(str) that uses a for...of loop and a switch to count vowels (a, e, i, o, u -- case insensitive).

Q54. Write a function that uses a while loop to compute base raised to the power exp (assume exp >= 0, no Math.pow).

Q55. Write a program that prints a hollow square of * characters with side length n. Use nested loops and if to decide star vs space.

*****
*   *
*   *
*   *
*****

Q56. Trace through the following code and predict the output:

let result = "";
for (let i = 1; i <= 4; i++) {
  for (let j = 1; j <= 4; j++) {
    if (i === j) continue;
    if (j === 3) break;
    result += `(${i},${j}) `;
  }
}
console.log(result);

Q57. Write a function isPangram(str) that checks if a string contains every letter of the alphabet at least once. Use a loop and a Set.

Q58. Write a function using nested loops that finds all pairs from two arrays whose sum equals a target value.


Answer hints

QHint
Q1"" is falsy; " " is truthy (non-empty)
Q2= is assignment, not comparison; x becomes 10 (truthy)
Q4Only "d" prints -- 0, "", null are falsy
Q9True -- [] and {} are truthy; both are objects
Q12"string two" -- switch uses ===, no type coercion
Q263, 3, 3 -- var is function-scoped
Q34Just "done" -- condition is false initially
Q355 then "done" -- body runs once before check
Q38x goes 1, 4, 7, 10... wait, 10 is hit. Actually: 1, 4, 7, 10 -- it does terminate! Trick question: re-examine with x += 4 instead
Q430, 1, 2
Q440, 1, 2, 4 (3 is skipped)
Q490, 1, 2 -- break exits the switch, not the for loop
Q56Trace carefully: (1,2) (2,1) (3,1) (3,2) (4,1) (4,2)

<-- Back to 1.19 -- Conditionals and Loops (README)