Challenge - 5 Problems
While Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a simple while loop
What will be the output of the following JavaScript code?
Javascript
let count = 0; let result = ''; while (count < 3) { result += count + '-'; count++; } console.log(result);
Attempts:
2 left
💡 Hint
Remember the loop runs while count is less than 3, and count starts at 0.
✗ Incorrect
The loop runs while count is 0, 1, and 2. Each time it adds the current count and a dash. When count reaches 3, the loop stops, so '0-1-2-' is printed.
❓ Predict Output
intermediate2:00remaining
While loop with break statement
What will be printed by this code?
Javascript
let i = 1; let output = ''; while (i <= 5) { if (i === 3) break; output += i; i++; } console.log(output);
Attempts:
2 left
💡 Hint
The loop stops when i equals 3.
✗ Incorrect
The loop adds '1' and '2' to output. When i becomes 3, the break stops the loop before adding '3'. So output is '12'.
❓ Predict Output
advanced2:00remaining
While loop with nested condition
What is the final value of variable sum after running this code?
Javascript
let n = 5; let sum = 0; while (n > 0) { if (n % 2 === 0) { sum += n; } n--; }
Attempts:
2 left
💡 Hint
Add only even numbers from 5 down to 1.
✗ Incorrect
Even numbers between 5 and 1 are 4 and 2. Their sum is 6.
❓ Predict Output
advanced2:00remaining
While loop with post-increment in condition
What will this code output?
Javascript
let x = 0; let output = ''; while (x++ < 3) { output += x; } console.log(output);
Attempts:
2 left
💡 Hint
Remember x++ returns the value before incrementing.
✗ Incorrect
The condition checks x before incrementing. Loop runs while x is 0,1,2. Inside loop, x is incremented, so output adds 1,2,3.
❓ Predict Output
expert2:00remaining
While loop with complex condition and variable update
What is the output of this code snippet?
Javascript
let a = 1; let b = 10; let result = ''; while (a < b) { result += a + ','; a *= 2; b -= 3; } console.log(result);
Attempts:
2 left
💡 Hint
Check how a and b change each loop and when the condition fails.
✗ Incorrect
Loop 1: a=1,b=10 (1<10) add '1,'; a=2,b=7
Loop 2: a=2,b=7 (2<7) add '2,'; a=4,b=4
Condition: a=4,b=4 (4<4) false, stop. So output is '1,2,'