loops
In this module we'll discuss loops.
File Location
You should be located in the loops.js
file:
Description
Loops allow us to repeatedly run a block of code until a condition is met.
You need to do something a lot that involves counting, like list all one million users in your database? You're going to probably need a loop.
Sample Code
Let's look at a for loop
. It's very common, and you need to know how to write one. There are other types of loops, but this is a good place to start learning.
Quick thought: What if we wanted to print a range of numbers all the way to 100.
That would be dreadfully inefficient to have to write. A for loop can take care of this in no time, and in only 3 lines of code.
Syntax
Let's look at the syntax of a for loop. This takes a lot of practice and a lot of reading. Then, more practice.
Here's the structure:
And another example:
This is the starting point. We're starting to count from 1.
This is the conditional section, the condition to be met. As long as
i
is under 10 or equal to 10, keep going.This is what it does when it keeps going.
i++
is shorthand for saying, add 1 to i.
So here are some thoughts for you: 1. This loop is going to start at 1. 2. It's going to check if i is less than 10. It is. It's 1. 3. So we're going to execute the third spot: i++
. So add 1 to i. 4. Then, print i to the console. The value of i prints each time until it reaches 10.
Practice
The only way to learn is to write a bunch of loops. More than you think you need. Let's give you a few examples:
Write a loop that counts to 50 by 5s. Starts at 0.
Write a loop that starts at 20 and counts down to 1. It subtracts one each time.
Write a for loop that starts at 3, and increments by 5, but doesn't go over 30.
Answers
Write a loop that counts to 50 by 5s. Starts at 0:
Write a loop that starts at 20 and counts down to 1. It subtracts one each time:
Write a for loop that starts at 3, and increments by 5, but doesn't go over 30:
More Practice
You should write 10 loops. Challenge yourself. This is the way to learn. Here are a couple starter ideas:
Count to 200 by 25s. Start on 25.
Count to 10 by 2s. Start at 6.
Count to 10 by 5s. Start at 100.
Write a loop that calls a function every time it iterates:
Keep going with examples like these until you can write a simple for loop without looking at other examples.
Last updated