Menu
Coddy logo textTech

Nested Loop

Part of the Fundamentals section of Coddy's JavaScript journey — lesson 44 of 77.

A nested loop is simply a loop inside another loop. The inner loop will complete all its iterations for each single iteration of the outer loop.

A good analogy for this is a clock: for each hour (outer loop), the minute hand (inner loop) must complete its full 60-minute cycle.

Example of a nested loop:

for (let x = 0; x < 2; x++) {
	for (let y = 0; y < 2; y++) {
		console.log(x, y);
	}
}

// This will output:
// 0 0
// 0 1
// 1 0
// 1 1

The outer loop (x) runs twice, and for each of those times, the inner loop (y) runs twice.

challenge icon

Challenge

Beginner

Write a program that finds all pairs of numbers that add up to n using numbers from 1 to n - 1.

For example if n = 6, the output should be:

1 5
2 4
3 3
4 2
5 1

Because:

1 + 5 = 6
2 + 4 = 6
3 + 3 = 6
4 + 2 = 6
5 + 1 = 6

Cheat sheet

A nested loop is a loop inside another loop. The inner loop completes all its iterations for each single iteration of the outer loop.

for (let x = 0; x < 2; x++) {
	for (let y = 0; y < 2; y++) {
		console.log(x, y);
	}
}

// Output:
// 0 0
// 0 1
// 1 0
// 1 1

The outer loop runs twice, and for each iteration, the inner loop runs twice completely.

Try it yourself

let n = parseInt(inp); // Don't change this line

// Write your code below
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals