loops
In this module we'll discuss loops.
File Location
You should be located in the loops.js file:
└── 2-CSS-Basics
└── 3-JavaScript-Basics
07-loops.js <----Work hereDescription
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.
console.log(1);
console.log(2);
console.log(3);
console.log(4);
console.log(5);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.
for (var i = 1; i < 101; i += 1){
console.log(i);
}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:
for (setup; test expression; increment) {
body;
}And another example:
//1 //2 //3
for ( var i = 1; i <= 10; i++){
console.log("Number:", i);
}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
iis 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:
for(var i = 0; i <= 50; i+=5){
console.log(i);
}Write a loop that starts at 20 and counts down to 1. It subtracts one each time:
for (var i = 20; i > 1; i--){
console.log(i);
}Write a for loop that starts at 3, and increments by 5, but doesn't go over 30:
for(var i = 3; i < 30; i += 5){
console.log(i)
}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:
function pacersWon(){
console.log("Pacers won!");
}
for(var i = 0; i < 5; i++){
pacersWon();
}Keep going with examples like these until you can write a simple for loop without looking at other examples.
Last updated