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 1The outer loop (x) runs twice, and for each of those times, the inner loop (y) runs twice.
Challenge
BeginnerWrite 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 1Because:
1 + 5 = 6
2 + 4 = 6
3 + 3 = 6
4 + 2 = 6
5 + 1 = 6Cheat 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 1The 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 belowThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Type Coercion7Bill Split Calculator
Welcome MessageCalculating The Tip And Total2Variables
NumbersStringBooleanNaming ConventionsEmpty VariablesRecap - Initialize VariablesConstants3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsStrict vs Loose EqualityRecap - Simple Math6Basic IO
OutputOutput with VariablesType Conversion - Part 1Type Conversion - Part 2Recap - Till 120Recap - True or False