Lecture: Loops

Imagine if we wanted to print out ALL the elements of an array. Or the even numbers between 0 and 100. Or even just repeat the same thing - like "text my mom something nice" or "text my ex something mean" - 100 times?

console.log(1)
console.log(2)
console.log(3)
console.log(4)
console.log(5)
console.log(6)
console.log(7)
console.log(8)
console.log(9)
console.log(10)
console.log(11)
console.log(12)
console.log(13)
console.log(14)
console.log(15)

That looks pretty tedious! What if we wanted to up to 100, or 1,000, or 1,000,000?!

Computers are not very smart, but they are very good at doing repetetive tasks. How? They use loops!

for (let i = 0; i < 100; i++) {
  console.log(i)
}

So what's going on here? Let's break it down:

The loop has four major sections:

  1. Initialization: let i = 0
  2. Condition: i < 100
  3. Increment: i++
  4. Body: console.log(i)

These are all just examples, you can put anything you want in any of the four sections (including nothing at all!), but the vast majority of the time all four sections have something in them.

Initialization

The initialization is where you set up the variables that you need for your loop. The most common is let i = 0; but you can start at anything, for example: 1 or 1000000, depending on what your program is doing.

Challenge Question: What would the initialization be if we wanted to start our index at the END of an array and work backwards?

Condition

The loop will execute the body repeatedly until the condition evaluates to false. Each execution of the body is called an iteration.

Challenge Question: What would the condition be if we wanted to start our index at the END of an array and work backwards? What about if we started at the BEGINNING of an array and work forwards to the end?

Increment

The increment is where you update the variables at the end of each iteration. The most common is i++ but you can do anything, for example: i += 2 or i *= 2, depending on what your program is doing.

Challenge Question: What would the increment be if we wanted to start our index at the END of an array and work backwards?

Body

The body is the meat of your loop. The rest is just figuring out where you start, where you end, and what the step size is. The body gets executed over and over again until the condition evaluates to false.

Challenge Question: Now that we have all the pieces, write a program that iterates through an array from the back to the front and prints out only the values at the odd indices.

const myArray = [7, 24, 25, 9, 40, 41, 11, 60, 61];
// your program should output: 60,41,9,24

Challenge Question: write a program that iterates through an array from the front to the back and prints out only the odd values.

const myArray = [7, 24, 25, 9, 40, 41, 11, 60, 61];
// your program should output: 7,25,9,41,11,61