๐ŸŽ“ Velnov

๐ŸŸจ JavaScript ยท Topic 7 of 20

Loops โ€” JavaScript Questions with Answers

30 practice questions on Loops, 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 ยท 18 medium ยท 9 hard ยท Part of JavaScript: The language of the web - basics to advanced, 20 topics.

Key concepts in this topic

for loopSyntaxOff-by-onebreakcontinuewhiledo-whileDebuggingfor...ofIterablesfor...inObjectsGotchasforEachCallbackssomeEarly exitClosureslet vs varEvent loopletReverse iterationreverse()Accumulator

Jump to: Easy ยท Medium ยท Hard

Easy questions (3)

Q1. easy

What are the three parts of a classic for loop? for (A; B; C)

for (let i = 0; i < 5; i++) {
  console.log(i);   // 0 1 2 3 4
}
  1. A Initialisation; condition; update
  2. B Start; end; step size
  3. C Variable; array; index
  4. D Condition; body; return

Answer: A โ€” Initialisation; condition; update

for (let i = 0; i < 5; i++) means: create i, keep going while the condition holds, and run the update after each pass.

for loopSyntax

Q2. easy

How many times does this run? for (let i = 0; i < 5; i++) { }

  1. A 5 times (i = 0,1,2,3,4)
  2. B 4 times
  3. C 6 times
  4. D Infinite

Answer: A โ€” 5 times (i = 0,1,2,3,4)

Starting at 0 and stopping before 5 gives five iterations. Starting at 0 with < length is the standard array pattern.

for loopOff-by-one

Q5. easy

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

let i = 10;
while (i < 5) { console.log("never"); }
do { console.log("once"); } while (i < 5);
  1. A do...while checks the condition AFTER the body, so it always runs at least once
  2. B They are identical
  3. C while runs at least once
  4. D do...while cannot use break

Answer: A โ€” do...while checks the condition AFTER the body, so it always runs at least once

while may run zero times if the condition starts false; do...while guarantees one execution - handy for menus and input prompts.

whiledo-while

Medium questions (18)

Q3. medium

What does break do inside a loop?

for (const n of nums) {
  if (n > 100) break;   // stop searching
  console.log(n);
}
  1. A Exits the loop immediately
  2. B Skips one iteration
  3. C Pauses the loop
  4. D Restarts the loop

Answer: A โ€” Exits the loop immediately

break stops the loop entirely and continues after it - useful once you have found what you were searching for.

breakcontinue

Q4. medium

What does continue do?

for (let i = 0; i < 5; i++) {
  if (i === 2) continue;
  console.log(i);   // 0 1 3 4
}
  1. A Skips the rest of the current iteration and moves to the next one
  2. B Exits the loop
  3. C Restarts from zero
  4. D Nothing

Answer: A โ€” Skips the rest of the current iteration and moves to the next one

continue jumps to the next iteration, skipping the remaining statements in the body for this pass only.

continuebreak

Q6. medium

What causes an INFINITE loop most often?

let i = 0;
while (i < 5) {
  console.log(i);
  // forgot i++  -> infinite!
}
  1. A Forgetting to update the variable the condition depends on
  2. B Using const
  3. C Using break
  4. D Nesting loops

Answer: A โ€” Forgetting to update the variable the condition depends on

If nothing changes the condition, it stays true forever and the browser tab freezes. Always ensure the loop makes progress toward termination.

whileDebugging

Q7. medium

What does for...of iterate over?

for (const fruit of ["apple", "mango"]) {
  console.log(fruit);   // apple, mango
}
  1. A The VALUES of an iterable (array, string, Map, Set)
  2. B The keys/indexes
  3. C Object properties
  4. D Only numbers

Answer: A โ€” The VALUES of an iterable (array, string, Map, Set)

for...of gives you each value directly - the cleanest way to loop an array when you do not need the index.

for...ofIterables

Q8. medium

What does for...in iterate over?

const user = { name: "Ana", age: 21 };
for (const key in user) {
  console.log(key, user[key]);
}
  1. A The KEYS (property names) of an object - or indexes of an array
  2. B The values
  3. C Only arrays
  4. D Nothing

Answer: A โ€” The KEYS (property names) of an object - or indexes of an array

for...in walks enumerable property names. Use it for plain objects; for arrays prefer for...of or forEach, because for...in gives string indexes and can include inherited properties.

for...inObjects

Q10. medium

Which loop is best for iterating an array's values?

  1. A for...of (or forEach) - clear and index-free
  2. B for...in
  3. C do...while
  4. D A while loop with a counter

Answer: A โ€” for...of (or forEach) - clear and index-free

for...of reads naturally and avoids index bugs. Use a classic for loop when you need the index or must skip/step, and forEach when you like the callback style.

for...offorEach

Q11. medium

What is the output? const arr = [10, 20, 30]; arr.forEach((v, i) => console.log(i, v));

  1. A 0 10 / 1 20 / 2 30 - the callback receives (value, index)
  2. B 10 0 / 20 1 / 30 2
  3. C Only the values
  4. D Error

Answer: A โ€” 0 10 / 1 20 / 2 30 - the callback receives (value, index)

forEach passes (value, index, array) to the callback. Note the VALUE comes first, which surprises people expecting index first.

forEachCallbacks

Q14. medium

Why does let fix the loop-closure problem?

  1. A let creates a NEW binding for each iteration, so every callback captures its own value
  2. B let is faster
  3. C let delays the callbacks
  4. D It does not fix it

Answer: A โ€” let creates a NEW binding for each iteration, so every callback captures its own value

The specification re-binds a let loop variable per iteration, giving each closure its own copy. var has a single shared binding for the whole function.

letClosures

Q15. medium

How do you loop BACKWARDS through an array?

  1. A for (let i = arr.length - 1; i >= 0; i--)
  2. B for (let i = arr.length; i > 0; i++)
  3. C for (const x of arr.reverse()) // mutates!
  4. D for (let i = 0; i < arr.length; i--)

Answer: A โ€” for (let i = arr.length - 1; i >= 0; i--)

Start at the last index (length - 1), continue while >= 0, and decrement. Option C works but reverse() MUTATES the original array - use [...arr].reverse() to avoid that.

Reverse iterationreverse()

Q16. medium

What is the output? let sum = 0; for (let i = 1; i <= 3; i++) sum += i; console.log(sum);

  1. A 6
  2. B 3
  3. C 5
  4. D 0

Answer: A โ€” 6

1 + 2 + 3 = 6. The accumulator pattern (start at 0, add each value) is the most common loop use.

Accumulatorreduce

Q17. medium

How many times does the inner body run? for (let i = 0; i < 3; i++) for (let j = 0; j < 4; j++) { }

  1. A 12 - 3 x 4
  2. B 7
  3. C 3
  4. D 4

Answer: A โ€” 12 - 3 x 4

The inner loop runs fully for every outer iteration, so counts multiply. Nested loops are common for grids and tables - watch out for performance with large data.

Nested loopsComplexity

Q19. medium

What does this loop over? for (const [key, value] of Object.entries(obj))

const user = { name: "Ana", age: 21 };
for (const [k, v] of Object.entries(user)) {
  console.log(`${k}: ${v}`);
}
  1. A Each key/value pair of the object, destructured into two variables
  2. B Only keys
  3. C Only values
  4. D Nothing - objects are not iterable

Answer: A โ€” Each key/value pair of the object, destructured into two variables

Object.entries returns [key, value] arrays; destructuring in the loop header unpacks them. The modern, readable way to iterate objects (alternatives: Object.keys / Object.values).

Object.entriesDestructuring

Q20. medium

What is the output? for (const ch of "hi") console.log(ch);

  1. A h then i - strings are iterable
  2. B hi
  3. C 0 1
  4. D Error

Answer: A โ€” h then i - strings are iterable

for...of works on any iterable, including strings (character by character), arrays, Maps, Sets and NodeLists.

IterablesStrings

Q23. medium

What does for (;;) do?

  1. A Creates an infinite loop (all three parts omitted) - needs a break inside
  2. B SyntaxError
  3. C Runs once
  4. D Runs zero times

Answer: A โ€” Creates an infinite loop (all three parts omitted) - needs a break inside

All three clauses are optional; an absent condition is treated as true. Equivalent to while (true) - use break to exit.

Infinite loopswhile(true)

Q24. medium

Which loop should you choose when you do not know how many iterations are needed?

  1. A while - it is condition-driven rather than count-driven
  2. B for - always
  3. C for...of
  4. D forEach

Answer: A โ€” while - it is condition-driven rather than count-driven

Use for/for...of when iterating a known collection or count; use while when looping until some state changes ('until the user quits', 'until the queue is empty').

whileChoosing loops

Q26. medium

What is the modern way to repeat something N times without needing the index?

const squares = Array.from({length: 5}, (_, i) => i * i);
// [0, 1, 4, 9, 16]
  1. A for (let i = 0; i < n; i++) - or Array.from({length: n}).forEach(...)
  2. B repeat(n)
  3. C times(n)
  4. D loop n

Answer: A โ€” for (let i = 0; i < n; i++) - or Array.from({length: n}).forEach(...)

JavaScript has no times() helper. A plain for loop is clearest; Array.from({length: n}, (_, i) => ...) is handy when you want to BUILD an array of n items.

Array.fromRepetition

Q28. medium

What does the map() method do compared with a for loop?

  1. A Builds a NEW array by transforming every element - a loop that returns a result
  2. B Loops without returning anything
  3. C Filters elements
  4. D Sorts the array

Answer: A โ€” Builds a NEW array by transforming every element - a loop that returns a result

map is a declarative loop for transformation: [1,2,3].map(n => n * 2) gives [2,4,6]. It never mutates the original. (forEach is the version that returns nothing.)

mapforEachArray methods

Q29. medium

How do you loop over a NodeList returned by querySelectorAll?

document.querySelectorAll(".item").forEach(el => el.classList.add("on"));
  1. A for...of or forEach - NodeLists are iterable and have forEach
  2. B Only a classic for loop works
  3. C You must convert with Array.from() first, always
  4. D NodeLists cannot be looped

Answer: A โ€” for...of or forEach - NodeLists are iterable and have forEach

Modern NodeLists support both for...of and forEach. Convert with Array.from(list) or [...list] only when you need array methods like map or filter.

DOMNodeList

Hard questions (9)

Q9. hard

What is the output? for (const i in ["a", "b"]) console.log(typeof i);

  1. A "string" twice - for...in gives indexes as STRINGS
  2. B "number" twice
  3. C "a" "b"
  4. D undefined

Answer: A โ€” "string" twice - for...in gives indexes as STRINGS

Object keys are always strings, so array indexes come out as "0" and "1". This breaks arithmetic (i + 1 becomes "01") - one reason to avoid for...in on arrays.

for...inGotchas

Q12. hard

Can you break out of a forEach loop?

// early exit alternatives:
for (const x of arr) { if (x > 10) break; }
arr.some(x => x > 10);   // stops at first true
  1. A No - break is not allowed; use for...of, some(), or every() instead
  2. B Yes, with break
  3. C Yes, with return
  4. D Yes, with continue

Answer: A โ€” No - break is not allowed; use for...of, some(), or every() instead

forEach always visits every element; break is a syntax error inside it, and return only exits the current callback (acting like continue). For early exit use for...of with break, or some()/find().

forEachsomeEarly exit

Q13. hard

What is the output? for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 0); }

for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0);   // 0 1 2
}
  1. A 3 3 3 - var is function-scoped, so all callbacks share one i
  2. B 0 1 2
  3. C 0 0 0
  4. D undefined x3

Answer: A โ€” 3 3 3 - var is function-scoped, so all callbacks share one i

The timeouts run after the loop finishes, when i is 3. Changing var to let creates a fresh binding per iteration and prints 0 1 2 - the classic demonstration of why let exists.

  • The single most famous JavaScript interview question.

Closureslet vs varEvent loop

Q18. hard

In nested loops, what does a plain break exit?

outer:
for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    if (j === 1) break outer;   // exits BOTH
  }
}
  1. A Only the INNERMOST loop containing it
  2. B All loops
  3. C The function
  4. D Nothing

Answer: A โ€” Only the INNERMOST loop containing it

break leaves just its own loop. To exit both, use a labelled break, a flag variable, or extract the loops into a function and return.

Labelsbreak

Q21. hard

Why is caching the length sometimes suggested? for (let i = 0, n = arr.length; i < n; i++)

  1. A It avoids re-reading .length each iteration - a micro-optimisation, rarely needed today
  2. B It is required for correctness
  3. C It prevents infinite loops
  4. D It changes the iteration order

Answer: A โ€” It avoids re-reading .length each iteration - a micro-optimisation, rarely needed today

Modern engines optimise .length access, so this matters only in extreme hot loops. Readability usually wins - but it IS important if the loop modifies the array's length.

PerformanceOptimisation

Q22. hard

What is the danger of modifying an array WHILE looping over it by index?

// safest:
arr = arr.filter(x => x >= 0);
// or loop backwards when removing
  1. A Removing items shifts positions, so the loop can SKIP elements
  2. B It throws an error
  3. C The array becomes read-only
  4. D Nothing happens

Answer: A โ€” Removing items shifts positions, so the loop can SKIP elements

After splice(i, 1), every later element moves left while i still advances - skipping one. Loop backwards, or build a new array with filter().

splicefilterMutation

Q25. hard

What is the output? const arr = [1, 2, 3]; for (let i = 0; i < arr.length; i++) { if (i === 1) arr.push(99); } console.log(arr.length, i_ran_times = "?");

// safe: iterate a copy
for (const x of [...arr]) { arr.push(x); }   // terminates
  1. A Length 4, and the loop runs 4 times - the condition re-reads the GROWN length each pass
  2. B Length 4, but the loop still runs only 3 times
  3. C Length 3 - push inside a loop is ignored
  4. D Infinite loop

Answer: A โ€” Length 4, and the loop runs 4 times - the condition re-reads the GROWN length each pass

i < arr.length is re-evaluated every iteration. At i=1 the push makes length 4, so the loop continues to i=3 and runs four times instead of three. Pushing on every pass would loop forever - which is why mutating an array while looping over it is dangerous.

MutationTracingInfinite loops

Q27. hard

What is the output? let i = 0; while (i < 3) { i++; if (i === 2) continue; console.log(i); }

  1. A 1 then 3
  2. B 1 2 3
  3. C 1 2
  4. D 2 3

Answer: A โ€” 1 then 3

i increments first, so values are 1, 2, 3. When i is 2, continue skips the log. Note the increment comes BEFORE continue here - if it came after, this would loop forever.

continuewhileTracing

Q30. hard

What is the output? console.log([1,2,3].reduce((a, b) => a + b, 0));

const total = cart.reduce((sum, item) => sum + item.price, 0);
  1. A 6 - reduce accumulates the array into a single value
  2. B [1,2,3]
  3. C 123
  4. D 0

Answer: A โ€” 6 - reduce accumulates the array into a single value

reduce runs a callback over each element carrying an accumulator: 0+1=1, 1+2=3, 3+3=6. It is the loop-with-a-running-total expressed as one call.

reduceAccumulator

Practice โ€œLoopsโ€ as a quiz