Nested For Loops
Loops offer a quick and easy way to do something repeatedly. There are a handful of loop statement in JavaScript, such as: for, for/in, and while to name a few. Today we will learn about nested for loops.
Table of Contents
Prerequisites
- Basic JavaScript Syntax
- Basic Data Types
- Arrays
- Basic For Loops
Objectives
By the end of this lesson developers should be able to:
- Utilize
nested for loopsto output data to the console - Distinguish the difference between a
for loopand anested for loop
Basic For Loops
A for loops basic functionality is to continuously execute a specific block of code until a test expression is evaluated to false.
Example:
const captains = ['Picard', 'Kirk', 'Janeway', 'Sisko']
for(let i = 0; i < captains.length; i++){
console.log(`${captains[i]}`)
}
The above example will iterate over the array of Captains and console.log each Captains' name.
Nested For Loops
We commonly utilize nested for loops to place one loop inside of another, this allows us to dynamically combine data to output a desired result.
We Do
Let's make our console act out a Star Trek: Short Trek where Captain Picard get stuck in a time loop.
for(let i = 3; i > 0; i--){
console.log("Mr. Crusher! Engage in:")
for(let j = 3; j > 0; j--){
console.log(j)
}
}
As you can see above we are defining two separate loops:
The
Outer Loop: Where we defineiand say for each timeiis greater than 0; we want the console to output:Mr Crusher! Engage in:The
Inner Loop: Where we definejand say for each timejis greater than 0; we want the console to output:j
So what is happening inside this Nested For Loop?
By nesting the Inner Loop inside of the Outer Loop we are able to:
- Execute our
Outer Loopwhich outputs Captain Picard's command once - Then
Inner Loopis executed and outputs itsconsole loguntil its condition is evaluated as true; ie:3,2,1 - Then the
Out Looppicks up where it left off and outputs Captain Picard's command again because its condition has not been met - Which then causes the the
Inner Loopto execute again and repeat step two listed above - Then we run through step one and two one more time due to the
Out Loopnot ceasing to execute until its condition is evaluated to true
Challenge
Can you decipher what is going on here in the code below?
let captainsOrder = "Mr. Crusher! Engage in:"
let countDown = [3, 2, 1, 'Engage!']
for(let i = 3; i > 0; i--){
console.log(captainsOrder)
for(let j = 0; j < countDown.length; j++){
console.log(countDown[j])
}
}



Top comments (0)