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:
let rows = 2;
let cols = 2;
for (let x = 0; x < rows; x++) {
for (let y = 0; y < cols; y++) {
console.log(x, y);
}
}
// This will output:
// 0 0
// 0 1
// 1 0
// 1 1The outer loop (x) runs rows times, and for each of those times, the inner loop (y) runs cols times. Each loop has its own counter: y starts again from 0 every time the outer loop runs, while rows and cols stay the same and only tell the loops when to stop.
Challenge
BeginnerWrite a program that prints a rectangle of asterisks (*) with a given width and height.
Input: Two integers: width and height (the starter code already reads them).
For example:
If width = 5 and height = 3, the output should be:
*****
*****
*****If width = 4 and height = 6, the output should be:
****
****
****
****
****
****Use a new counter for each loop (for example i for the rows and j for the stars in a row) and compare it with height or width. Don't change height and width themselves: every row needs width again.
Try it yourself
let width = parseInt(inp[0]); // Don't change this line
let height = parseInt(inp[1]); // Don't change this line
// Write your code below
This 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 FalsePractice on your own: Online JavaScript compiler