IN THIS LESSON

What is a for loop?

Sometimes we need our programs to do something over and over again. Like a game with multiple rounds, or filter through every student in a class. In programming, if we want our programs to do the same thing repeatedly. we can use a structure called a loop. Use a for loop in JavaScript to efficiently execute a task multiple times without duplicating code. Today, we'll specifically explore the classic for loop.

Structure of a for loop

A for loop has 2 main sections: the head and the body.

Initialization - The initialization part of a loop sets the starting point or initial value for the loop variable. It occurs before the loop begins and is usually used to declare and initialize the loop variable. This step helps establish the initial conditions for the loop's execution.

Condition - The conditions part of a loop determines when the loop continues or terminates based on a specified condition.

Increment - The increment part of a loop updates the loop variable, progressing it towards the desired condition. It typically involves incrementing or decrementing the variable, ensuring the loop moves towards its endpoint. This step is crucial for controlling the loop's progress and preventing an infinite loop.

The head is made up of: The Initialization, the Condition, and the Increment. Only the first two have semi colons (;) after them.

The Loop body - The code body of a loop is the set of instructions enclosed in curly braces. It executes during each iteration, defining the task to be repeated as long as the loop condition is true.

for (let i = 0; i < 5; i++) { console.log("i:", i)}Initializationwhere theloop beginsConditionif this is true,keep loopingIncrementwhat to changewith each loop5.1 For LoopsLoop Bodythe code that runs witheach iteration of the loop

Click "Run Pen" in CodePen to execute the code. Feel free to experiment with the loop to observe its functionality and understand how it operates.

How for Loops Work

Our loop needs an iterator value to work. Because programmers are too lazy to type "iterator", the iteration variable is pretty much always i.

The loop then uses that i to decide if it should run the loop's body or not by checking the condition. If the condition is true, the loop body runs once.

But, how do we change the value of i so our loop will stop? After each iteration is run, the increment section runs. In this example it adds 1 to i. That's what that ++ operator does. It adds 1 to whatever value it's next to. It's the same as writing i += 1.

Then the cycle repeats! The loop will stop once the condition isn't true. Below is an image of this entire process (it only goes to 2, but every loop works the same).

for (let i = 0; i < 2; i++) { console.log(i)}console.log("Done")Given this loop:5.2 For Loop Stagesi = 0i < 2console.log(i)i++1 < 2console.log(i)i++i < 2 console.log("Done")i is 00 < 2 is trueLog 0i is now 11 < 2 is trueLog 1i is now 22 < 2 is falseLog "Done"initializationconditional checkloop bodyincrementconditional checkloop bodyincrementconditional checkLeave loopoutside codeHere’s exactly what would happen:
// Output for this loop
0
1
"Done"

Looping with Numbers

While almost 99% of the time our loops will just go up by 1, we don't have to. Lets start at 1, and go up by 2, so we can log every odd number from 1 to 10.

for (let i = 1; i < 10; i += 2) {
  console.log(i)
}
1
3
5
7
9

Incrementing and Decrementing

By that same token, there's no need to only go up either. The increment section can also be used to decrement as well. Since i++ goes up by one, i-- goes down by one. And no, it's just those two, there's no other shorthand. For anything else just use i -=. But let's do a count down!

for (let i = 3; i > 0; i--) {
  console.log(i)
}
console.log('GO!')
3
2
1
GO!

Click "Run Pen" in CodePen to execute the code. Feel free to experiment with the loop to observe its functionality and understand how it operates.

Return

You can use loops in a function, and if you use return in a loop, it behaves a lot like break. Except instead of just bailing on the loop, it also skips the rest of the function. Below, note that neither the looped 5 nor the "I should not appear" message get logged.

const loopAndGive5 = () => {
  for (let i = 1; i < 10; i++) {
    if (i === 5) {
      return i
    }
    console.log(i)
  }
  console.log("I should not appear")
}

let five = loopAndGive5()
console.log('OUTSIDE!')
console.log('five here:', five)
1
2
3
4
OUTSIDE!
five here: 5

🎉 Congratulations! You've successfully grasped the basic fundamentals of loops. Now, let's reinforce your learnings with some hands-on practice. Below are prompts to help you strengthen your skills. Please use the CodePen link provided to write and test your code, press Run Pen to activate the terminal:

Challenge 1: Write a loop that logs the numbers 0 - 7

Challenge 2: Write a reversed loop from 20 - 1 and log it to the console

Challenge 3: Write a loop that logs multiples of 2 up to 20

YOU DID IT!

Congratulations!!! That's all the coding knowledge you need to complete the Marcy Lab Code Challenges! Feel free to go back over any lessons that confused you, sometimes seeing something a second time after a break can be a big help. Access Code Challenge Here