0
0
Javascriptprogramming~5 mins

Nested loops in Javascript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a nested loop in JavaScript?
A nested loop is a loop inside another loop. The inner loop runs completely every time the outer loop runs once.
Click to reveal answer
beginner
How many times will the inner loop run in this code?<br><pre>for(let i = 0; i < 3; i++) {<br>  for(let j = 0; j < 2; j++) {<br>    console.log(i, j);<br>  }<br>}</pre>
The inner loop runs 2 times for each of the 3 outer loop runs, so 3 × 2 = 6 times total.
Click to reveal answer
beginner
Why use nested loops? Give a real-life example.
Nested loops help when you need to check combinations, like rows and columns in a grid or seats in a theater. For example, checking every seat in every row.
Click to reveal answer
intermediate
What is the output of this nested loop?<br><pre>for(let i = 1; i <= 2; i++) {<br>  for(let j = 1; j <= 3; j++) {<br>    console.log(i * j);<br>  }<br>}</pre>
The output is:<br>1<br>2<br>3<br>2<br>4<br>6<br>Because for i=1, j runs 1 to 3, printing 1×1, 1×2, 1×3; then for i=2, j runs 1 to 3, printing 2×1, 2×2, 2×3.
Click to reveal answer
intermediate
How can nested loops affect performance?
Nested loops can slow down programs because the total steps multiply. For example, two loops each running 100 times means 10,000 steps. Use them carefully.
Click to reveal answer
What does a nested loop mean in JavaScript?
ATwo loops running at the same time
BA loop that runs only once
CA loop inside another loop
DA loop that never ends
How many times will the inner loop run in this code?<br>
for(let i=0; i<4; i++) {<br>  for(let j=0; j<3; j++) {<br>    // code<br>  }<br>}
A12 times
B3 times
C7 times
D4 times
Which real-life example fits nested loops best?
ATurning on a single light bulb
BChecking every seat in every row of a theater
CCounting how many people are in a room
DWriting a single word
What is the output of this code?<br>
for(let i=1; i<=2; i++) {<br>  for(let j=1; j<=2; j++) {<br>    console.log(i + j);<br>  }<br>}
A2 3 3 4
B1 2 2 3
C3 4 5 6
D1 1 1 1
Why should you be careful with nested loops?
AThey are not allowed in JavaScript
BThey always cause errors
CThey only work with numbers
DThey can make code run slower because steps multiply
Explain what nested loops are and give a simple example in JavaScript.
Think about a loop inside another loop and how many times the inner loop runs.
You got /3 concepts.
    Describe a real-life situation where nested loops would be useful and why.
    Think about checking combinations or pairs, like rows and columns.
    You got /3 concepts.