0
0
Javascriptprogramming~20 mins

Why loops are needed in Javascript - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Loop Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a simple for loop
What will be the output of this JavaScript code?
let result = '';
for (let i = 1; i <= 3; i++) {
  result += i + ' ';
}
console.log(result.trim());
Javascript
let result = '';
for (let i = 1; i <= 3; i++) {
  result += i + ' ';
}
console.log(result.trim());
A1 2 3
B1 2 3 4
C3 2 1
D123
Attempts:
2 left
💡 Hint
Look at how the loop counts from 1 to 3 and adds each number with a space.
🧠 Conceptual
intermediate
1:30remaining
Why use loops instead of repeating code?
Why do programmers use loops instead of writing the same code many times?

Alice wants to print numbers 1 to 5. Which reason best explains why she should use a loop?
ALoops are harder to read than repeating code.
BLoops make the computer run slower.
CLoops make code shorter and easier to change if needed.
DLoops only work with numbers, not text.
Attempts:
2 left
💡 Hint
Think about what happens if Alice wants to print numbers 1 to 100 instead of 1 to 5.
Predict Output
advanced
2:30remaining
Output of nested loops
What will this JavaScript code print?
let output = '';
for (let i = 1; i <= 2; i++) {
  for (let j = 1; j <= 2; j++) {
    output += i + '-' + j + ' ';
  }
}
console.log(output.trim());
Javascript
let output = '';
for (let i = 1; i <= 2; i++) {
  for (let j = 1; j <= 2; j++) {
    output += i + '-' + j + ' ';
  }
}
console.log(output.trim());
A1-1 2-2 1-2 2-1
B1-1 2-1 1-2 2-2
C1-1 1-2 2-2 2-1
D1-1 1-2 2-1 2-2
Attempts:
2 left
💡 Hint
The outer loop controls i, inner loop controls j. Inner loop runs fully for each i.
Predict Output
advanced
2:00remaining
Loop with break statement output
What will this code print?
let text = '';
for (let i = 1; i <= 5; i++) {
  if (i === 3) break;
  text += i + ' ';
}
console.log(text.trim());
Javascript
let text = '';
for (let i = 1; i <= 5; i++) {
  if (i === 3) break;
  text += i + ' ';
}
console.log(text.trim());
A1 2 3
B1 2
C3 4 5
D1 2 4 5
Attempts:
2 left
💡 Hint
The loop stops when i equals 3 before adding it to text.
🧠 Conceptual
expert
1:30remaining
Why loops help with repetitive tasks
Imagine you want to send a greeting message to 100 friends. Which statement best explains why using a loop is the best choice?
ALoops let you write one message and send it 100 times automatically.
BLoops make the program slower because it repeats the message many times.
CLoops only work if all friends have the same name.
DLoops are only useful for counting numbers, not sending messages.
Attempts:
2 left
💡 Hint
Think about how much work it would be to write 100 lines of code to send messages.