How I tried to understand inside a Nested For Loop
Step by Step braking through the nested loop's iterations.
What is in this guide?
This is a basic guide where I tried to provide a step by step explanation of nested "for loops" in JavaScript. Breaking down the logic and iterations of the loop in detail by writing a program, which prints a solid square pattern on the browser console. I’m gonna explain what happens inside the mind of a loop as well as the iterations inside the nested loop and its working order.
Who is the guide for?
The guide is aimed for absolute beginners, who learned the basic JavaScript fundamentals or if you have confusion about the working order of "for loop".
Prerequisite: Basic JavaScript, Data Types (string, number), Operators(=, <, >, ++, +=
) and For loop.
Please, must give a feedback on this article, I am open to listen your valuable opinions, suggestions or if any mistake I have on this.
Introduction
Printing a Solid Square pattern is a beginner-level challenge. The challenge involves writing a program that prints a pattern makes the shape of a solid square to the console using a given character. Throughout this guide, we are going to write the program step by step using for loop to understand how the loop works, breaking down each step in detail of what happens inside when a for loop starts working.
Understanding the problem
Visualize a pattern in a shape of solid square made of any character, e.g., #
, in a 4 × 4 character grid size. That means four lines of four characters build the 4 x 4 size (column & row) solid square. Here's how it should look on the console.
It's necessary to understand the order of the pattern. Each new there is 4 characters (as column count), makes a row. We have to repeat this set in each new line 4 times to print our specific pattern.
Starting the Basic
First, let’s start by declaring variables to store some values. The first variable is size
, which stores the number 4, necessary to calculate for the pattern. The second is result
, which is assigned an empty string to store the final output. Since it will hold a string value, an empty string is assigned as the initial value for result
. (You can check the output at the end, what it returns, if you don’t store any empty string)
let size = 4;
let result = "";
(It is possible to doing it without initializing variables, but variable is used for better maintenance. Also, apart from the for loop, the program could be written using a while loop or in other methods but this is not our goal in this guide)
For instance, let’s write our basic “for loop” to understand the loop by breaking it down into small steps. Understanding the basics clearly will make our next step easier to consider.
for(let count = 0; count < size; count++){
result += "#";
}
console.log(result);
// Play with this code on a code playground or on console.
Understanding the Basic Setup
Variable Setup
size = 4;
- Number of times the loop iterates.result = "";
- Empty string to store the final output.Loop Initialization:
count = 0;
sets the starting value for the “For Loop”.Loop Conditioning:
count < size;
checks if count is less than size. The loop runs until the condition returns false.Loop Body:
result += "#";
appends a “#
” character toresult
on each for loop iteration.Update loop variable:
count++;
incrementscount
by 1 at the end of each iteration.count++
→count = count + 1
Incrementing is necessary, or the loop will run infinitely.
let text = “Hello”;
If I concatenate another value to the text
variable, like text += “World”;
it will append the string “World”
to its existing value “Hello”
, resulting in the output “HelloWorld”
. text += “World”
→ text = text + “World”
→ text = “Hello” + “World”
→ text = “HelloWorld”
What happens on each iteration?
size = 4;
result = ““;
Iteration 1:
count = 0;
→count < size;
→0 < 4
→ conditiontrue
→ Loop Bodyresult += “#";
→result = result + “#”;
→result = ““ + “#”
→result = “#”;
count++
→count = count + 1
→count = 0 + 1
→count = 1
Iteration 2:
count = 1;
→count < size;
→1 < 4
→true
→ Loop Bodyresult += “#";
→result = result + “#”;
→result = “#“ + “#”
→result = “##”;
count++
→count = count + 1
→count = 1 + 1
→count = 2
Iteration 3:
count = 2;
→2 < 4
→true
→ loop bodyresult += “#”;
→result
is“###”
count++
→count
is3
Iteration 4:
count = 3;
→3 < 4
→true
→ loop bodyresult += “#”;
→result
is“####”
count++
→count
is4
The End of Iteration:
count = 4;
→4 < 4
→false
→ loop stops.
console.log(result);
prints the final value from result
to the console. The final value is the last updated value. In this case, Output: ####
Building the Nest - Pattern Construction
So far, we have printed four "#"
characters(each character could consider as column) in one line (which we call row) using a For Loop. We need a total of 4 lines of similar character sets ####
to build the dimension for a square. ✅
We can achieve this by repeating our entire loop four times by placing the loop inside a new loop. This new loop creates each set ####
of characters four times. This forms a nested loop, meaning a loop inside another loop, an inner loop and an outer loop.
Let’s change our code according to our idea, also updating the variable names of the loops accordingly. The name for the inner loop is “col,” as it places characters through the column count, and for the outer loop, it is “row.”
for(let row=0; row < size; row++){
for(let col=0; col < size; col++){
result += "#";
}
}
Both loops will keep iterating until the conditions row < size
and col < size
become false. The row++
and col++
increment their own values one at a time in each iteration.
Now, if we run our code, the output will be like this: ################
, which is not our desired output. This happens because we didn't break into a new line for each one row.
- As the inner loop responsible for each set
####
, we will append the new line character"\n"
to the same variableresult
, after the inner loop but still within the body of the outer loop:result += "\n";
for(let row=0; row < size; row++){
for(let col=0; col < size; col++){
result += "#";
}
result += "\n"; // Appending new line.
}
- For each row, the inner loop appends the
“#”
character to the result. Once it is done adding the character and exits, the outer loop appends“\n”
to the result variable to move to a new line.
Braking the nested Iterations
➿ Outer Loop
Iteration1: row = 0
→ row < size
→ 0 < 4
→ true
-- Outer loop body
--- Inner loop
--- Iteration1: col = 0
: result += “#”
, so result
becomes “#”
, col++
--- Iteration2: col = 1
: result += “#”
, so result
becomes “##”
, col++
--- Iteration3: col = 2
: result += “#”
, so result
becomes “###”
, col++
--- Iteration4: col = 3
: result += “#”
, so result
becomes “####”
, col++
--- Inner loop exit
--result += "\n"
: A newline character is added, so result
becomes "####\n"
.
row++
→ increment value of row to 1
Iteration2: row = 1
→ row < size
→ 1 < 4
→ true
-- Outer loop body
--- Inner loop
--- Iteration1: col = 0
: result += “#”
, so result
becomes "####\n#"
, col++
--- Iteration2: col = 1
: result += “#”
, so result
becomes "####\n##"
, col++
--- Iteration3: col = 2
: result += “#”
, so result
becomes "####\n###"
, col++
--- Iteration4: col = 3
: result += “#”
, so result
becomes "####\n####"
, col++
--- Inner loop exit
-- result += "\n"
: A newline character is added, so result
becomes "####\n####\n"
.
row++
→ increment value of row to 2
subsequent process repeats
-Iteration3: row = 2
→ 2 < 4
→ true
→ "####\n####\n####\n"
→ row++
increment it’s value to 3
-Iteration4: row = 3
→ 3 < 4
→ true
→ "####\n####\n####\n####\n"
→ row++
increment it’s value to 4
-End Iteration: row = 2
→ 2 < 4
→ false
→ Stops
➿ Outer Loop Exits
Last line console.log(result);
prints the final value.
"####\n####\n####\n####\n"
is the final value the result variable stores at the end. The “\n”
will execute the line brake while print the output to console.
// The Final Code
let size = 4;
let result = "";
for(let row=0; row < size; row++){
for(let col=0; col < size; col++){
result += "#";
}
result += "\n";
}
console.log(result);
Conclusion
Performing complex tasks like iterating and displaying multi-dimensional data structures often involves using nested loops. So far, we have explored inside a nested loop of a basic program to build a foundation for basic understanding. We have broken down the iteration steps, for a basic loop and the nested one. I suggest to try writing different variations of this program, such as allowing the user to input for the size and character for the pattern, creating a rectangle pattern, or implementing the same program using a different method, for more practice.