Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
7 Loops of JavaScript
Next article icon

Nesting For Loops in JavaScript

Last Updated : 20 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Nesting for loops is crucial in JavaScript, enabling iteration over multi-dimensional data structures or performing complex tasks. It involves placing one loop inside another, where the outer loop executes for each iteration of the inner loop. This facilitates operations on multi-dimensional arrays or creating intricate patterns, essential for efficient data manipulation and traversal.

Table of Content

  • Types of Nested For Loops in JavaScript
  • For Loop within Another For Loop
  • For Loop within a For-In Loop
  • For Loop within a For-Of Loop

Types of Nested For Loops in JavaScript

In JavaScript, you can nest different types of loops to achieve the desired iteration. Common types include a For Loop within another For Loop, which is a standard nested loop for iterating over multi-dimensional arrays. Additionally, a For Loop within a For-In Loop combines index-based and property-based iteration, while a For Loop within a For-Of Loop mixes index-based and value-based iteration. These nested loops provide flexibility for handling complex data structures and iteration patterns.

For Loop within Another For Loop

This is the most straightforward approach, where a for loop is placed inside another for loop. It is often used for iterating over two-dimensional arrays or creating simple patterns.

Syntax:

for (let i = 0; i < outerLimit; i++) {
for (let j = 0; j < innerLimit; j++) {
// Code to execute
}
}

Example: The example below shows Nesting Loops where For Loop within Another For Loop in JavaScript.

JavaScript
for (let i = 1; i <= 10; i++) {     let row = "";     for (let j = 1; j <= 10; j++) {         row += (i * j) + "\t";     }     console.log(row); } 

Output
1    2    3    4    5    6    7    8    9    10     2    4    6    8    10    12    14    16    18    20     3    6    9    12    15    18    21    24    27    30     4    8    12    16    20    24    28    32    36    40     5    10    15    20    25    30    35    40    45    50     6    12    18    24    30    36    42    48    54    60     7    14    21    28    35    42    49    56    63    70     8    16...

For Loop within a For-In Loop

In this approach, a for loop is nested within a for-in loop. The for-in loop iterates over the properties of an object, and the inner for loop can perform additional iterations for each property.

Syntax

for (let key in obj) {
for (let i = 0; i < limit; i++) {
// Code to execute
}
}

Example: The example below shows Nesting Loops where For Loop within a For-In Loop in JavaScript.

JavaScript
const obj = { a: 1, b: 2, c: 3 };  for (let key in obj) {     console.log(`Key: ${key}`);     for (let i = 0; i < 3; i++) {         console.log(`  Value multiplied by ${i}: ${obj[key] * i}`);     } } 

Output
Key: a   Value multiplied by 0: 0   Value multiplied by 1: 1   Value multiplied by 2: 2 Key: b   Value multiplied by 0: 0   Value multiplied by 1: 2   Value multiplied by 2: 4 Key: c   Value multiplie...

For Loop within a For-Of Loop

In this approach, a for loop is nested within a for-of loop. The for-of loop iterates over iterable objects like arrays, and the inner for loop can perform additional iterations for each element.

Syntax

for (let value of arr) {
for (let i = 0; i < limit; i++) {
// Code to execute
}
}

Example: The example below shows Nesting Loops where For Loop within a For-Of Loop in JavaScript.

JavaScript
const arr = [1, 2, 3];  for (let value of arr) {     console.log(`Value: ${value}`);     for (let i = 0; i < 3; i++) {         console.log(`  Value plus ${i}: ${value + i}`);     } }  // Nikunj Sonigara 

Output
Value: 1   Value plus 0: 1   Value plus 1: 2   Value plus 2: 3 Value: 2   Value plus 0: 2   Value plus 1: 3   Value plus 2: 4 Value: 3   Value plus 0: 3   Value plus 1: 4   Value plus 2: 5 

Next Article
7 Loops of JavaScript
author
nikunj_sonigara
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Questions

Similar Reads

  • JavaScript For In Loop
    The JavaScript for...in loop iterates over the properties of an object. It allows you to access each key or property name of an object. [GFGTABS] JavaScript const car = { make: "Toyota", model: "Corolla", year: 2020 }; for (let key in car) { console.log(`${key}: ${car[key]}`); }
    3 min read
  • JavaScript For Loop
    JavaScript for loop is a control flow statement that allows code to be executed repeatedly based on a condition. It consists of three parts: initialization, condition, and increment/decrement. [GFGTABS] javascript // for loop begins when x=2 // and runs till x <= 4 for (let x = 2; x <= 4; x++)
    5 min read
  • JavaScript for...of Loop
    The JavaScript for...of loop is a modern, iteration statement introduced in ECMAScript 2015 (ES6). Works for iterable objects such as arrays, strings, maps, sets, and more. It is better choice for traversing items of iterables compared to traditional for and for in loops, especially when we have bre
    3 min read
  • How to break nested for loop using JavaScript?
    The break statement, which is used to exit a loop early. A label can be used with a break to control the flow more precisely. A label is simply an identifier followed by a colon(:) that is applied to a statement or a block of code. Note: there should not be any other statement in between a label nam
    3 min read
  • 7 Loops of JavaScript
    As a programmer, it's crucial to comprehend loops since they give you a means to repeatedly run a block of code. Loops are a fundamental idea in computer programming. Using loops has a number of advantages: Your code will be more effective if you use loops to automate repetitive processes and carry
    3 min read
  • JavaScript do...while Loop
    A do...while loop in JavaScript is a control structure where the code executes repeatedly based on a given boolean condition. It's similar to a repeating if statement. One key difference is that a do...while loop guarantees that the code block will execute at least once, regardless of whether the co
    4 min read
  • JavaScript Loops
    Loops in JavaScript are used to reduce repetitive tasks by repeatedly executing a block of code as long as a specified condition is true. This makes code more concise and efficient. Suppose we want to print 'Hello World' five times. Instead of manually writing the print statement repeatedly, we can
    3 min read
  • How to Loop through XML in JavaScript ?
    In JavaScript, looping over XML data is important for processing and extracting information from structured XML documents. Below is a list of methods utilized to loop through XML. Table of Content Using for loop with DOMParser and getElementsByTagNameUsing Array.from with DOMParser and childNodesUsi
    2 min read
  • Disadvantages of using for..in loop in JavaScript
    In this article, we will see what are the disadvantages of using for..in loop and how to solve those issues. Disadvantages of using for..in loop: Reason 1: When you add a property in an array or object using the prototype and any other array arr that has no relation with that property when you itera
    2 min read
  • Types of Arrays in JavaScript
    A JavaScript array is a collection of multiple values at different memory blocks but with the same name. The values stored in an array can be accessed by specifying the indexes inside the square brackets starting from 0 and going to the array length - 1([0]...[n-1]). A JavaScript array can be classi
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences