Home Web Front-end JS Tutorial How I tried to understand inside a Nested For Loop in JavaScript

How I tried to understand inside a Nested For Loop in JavaScript

Jan 05, 2025 pm 07:27 PM

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.

This article is originally published at Webdevstack.hashnode.dev

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.

How I tried to understand inside a Nested For Loop in JavaScript

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 = "";
Copy after login
Copy after login
Copy after login
Copy after login

(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.

let size = 4;
let result = "";
Copy after login
Copy after login
Copy after login
Copy after login

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 to result on each for loop iteration.

  • Update loop variable: count ; increments count by 1 at the end of each iteration.

    count → count = count 1

    Incrementing is necessary, or the loop will run infinitely.

Appending: adding a new value at the end of the existing value. For example, 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 → condition true → Loop Body

  • result = “#"; → result = result “#”; → result = ““ “#” → result = “#”;

  • count → count = count 1 → count = 0 1 → count = 1

Iteration 2:

  • count = 1; → count < size; → 1 < 4 → true → Loop Body

  • result = “#"; → result = result “#”; → result = “#“ “#” → result = “##”;

  • count → count = count 1 → count = 1 1 → count = 2

Iteration 3:

  • count = 2; → 2 < 4 → true → loop body

  • result = “#”; → result is “###”

  • count → count is 3

Iteration 4:

  • count = 3; → 3 < 4 → true → loop body

  • result = “#”; → result is “####”

  • count → count is 4

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.

?Each time the outer loop runs, it executes the inner loop, which iterates 4 times as well. This means four iterations of the outer loop will execute the inner loop four times, resulting in a total of 16 iterations for the inner loop. This is like the following.

How I tried to understand inside a Nested For Loop in JavaScript

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.”

let size = 4;
let result = "";
Copy after login
Copy after login
Copy after login
Copy after login

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 variable result, after the inner loop but still within the body of the outer loop: result = "n";
for(let count = 0; count < size; count++){
    result += "#";
}
console.log(result);
// Play with this code on a code playground or on console.
Copy after login
  • 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.

let size = 4;
let result = "";
Copy after login
Copy after login
Copy after login
Copy after login

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.

console.log(“Thanks for Reading”);

The above is the detailed content of How I tried to understand inside a Nested For Loop in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1672
14
PHP Tutorial
1276
29
C# Tutorial
1256
24
Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript in Action: Real-World Examples and Projects JavaScript in Action: Real-World Examples and Projects Apr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding the JavaScript Engine: Implementation Details Understanding the JavaScript Engine: Implementation Details Apr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Python vs. JavaScript: Development Environments and Tools Python vs. JavaScript: Development Environments and Tools Apr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

The Role of C/C   in JavaScript Interpreters and Compilers The Role of C/C in JavaScript Interpreters and Compilers Apr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

See all articles