Loops
Intro
- This tutorial covers JavaScript loops.
- It is recommended that you follow along with each section below. Paste or type the code into your own JavaScript file and view the variable or expression values either with console.logs or using the VS Code Debug sidebar.
- The example code for the entire tutorial series is at github.com/LearnByCheating/javascript-tutorial. There is a separate file or folder for each tutorial, including the To-Do List example project. The Readme file has instructions on how to run the code.
1. For loop
- A loop is a construct that repeatedly executes a block of code until or while a condition is met. There are a few different types of loops. We'll start with the for loop.
- The for loop is the classic loop structure in JavaScript.
Format:
for (initialize; condition; incrementExpression) {
statements;
}
- It starts with the keyword for, followed by three optional expressions in parentheses, each separated by a semicolon.
- First is an initialization expression that executes only one time before the loop begins. Typically this is used to initialize a counter variable.
- Next is a condition that is evaluated before each loop iteration. If it resolves to true, the loop executes. If not the loop terminates.
- Third is an increment expression that executes at the end of each loop iteration.
- Then comes the loop's block of statements that execute on each iteration.
Example:
for (let i = 1; i < 6; i++) {
console.log(i);
}
- In the above for loop example, the initialization expression sets a counter variable i to 1. This executes once before the loop begins.
- The second expression is the condition that determines if the loop continues to run. So as long as the variable i is less than 6, the loop will execute.
- The third expression runs after each iteration. Here we increment the counter variable i by 1.
- The loop body contains the statements that execute on each iteration of the loop. In this case it just logs the counter value to the console. When executed it will log 1, 2, 3, 4, 5.
- There are a couple of statements you can use in all JavaScript loops.
- Continue: The continue statement will skip the current iteration of the loop and go straight to the next iteration.
Example:
for (let i = 1; i < 6; i++) {
if (i === 4) continue;
console.log(i);
}
- The above example is the same as before, but this time we added an if statement that checks if the value of i is 4. If it is, it executes the continue statement. It will skip the rest of the code for this iteration and go on to the next.
- When executed, it will log 1, 2, 3, and 5. 4 is skipped.
- Break: The next statement you can use in all JavaScript loops is the break statement. This will terminate the loop.
Example:
for (let i = 1; i < 6; i++) {
if (i === 4) break;
console.log(i);
}
- The above example uses the same loop. The if statement checks if i is 4. If it is then the break statement gets executed and the loop terminates.
- When executed, it will log 1, 2, and 3, then terminate.
2. While loop
- While loops repeat through a block of code while the condition is true.
Format:
while (condition) {
statements;
}
- It starts with the keyword while, then comes the condition in parentheses.
- The condition is checked before each iteration of the loop. If it returns true, the loop executes. If false, the loop terminates.
Example:
let i = 1;
while (i < 6) {
console.log(i);
i++;
}
- The above example does the same thing our for loop did but the structure of the loop is a little different. This time we initialize a counter variable outside the loop.
- The condition checks that the counter, i, is less than 6.
- In the loop statements we log the counter's value to the console. Then a second statement increments the counter by 1.
- When executed it will log 1, 2, 3, 4, 5.
3. Do...While loop
- The Do...While loop is like the while loop except the condition comes after the block. So even if the condition is not met, the block will still run at least once.
Format:
do {
statements;
} while (condition);
Example:
let i = 1;
do {
console.log(i++);
} while (i < 6);
- In the above example, as with the while loop, we initialize a counter variable outside the loop.
- Use the keyword do followed by the block of code to execute.
- On each iteration the block logs the counter variable i and increments it in the same statement.
- After the closing curly brace comes the condition. As long as i is less than 6, the loop will execute again.
- When executed it will log 1, 2, 3, 4, 5.
4. For...Of loop (iterate over array elements)
- The for...of loop was introduced with ES6 in 2015. It is used to iterate over an array. It is an iterator. Iterators execute once for each element in a collection and don't need a condition.
Format:
for (const elem of arr) {
statements;
}
- Start with the keyword for,
- then in parentheses declare a variable to hold the array element for each iteration.
- followed by the keyword of
- then the array.
- Then put the loop statements to execute for each iteration in the block.
Example:
const arr = ['a', 'b', 'c', 'd', 'e'];
for (const elem of arr) {
console.log(elem);
}
- In the above example we have an array of single letters a through e assigned to variable arr.
- The for...of loop iterates through each element in the array and logs the element to the console.
- We set the variable name to elem, followed by of, then the array.
- When executed it will log 'a', 'b', 'c', 'd', 'e'.
Array forEach method
- The array forEach method does essentially the same thing as a for...of loop and may be a little more intuitive. This is covered in the Array tutorial.
arr.forEach((elem) => {
console.log(elem);
});
- You chain the forEach method to the array and pass in a callback function.
- In the callback argument, pass in a variable for each array element.
- Then in the method's block you can execute your code on the element. In this case we are just logging it to the console.
- When executed it will log 'a', 'b', 'c', 'd', 'e'.
5. For...In loop (iterate over object properties)
- The for...in loop iterates over an object's property names.
Format:
for (const property in object) {
statements;
}
- Start with the keyword for,
- then in parentheses declare a variable to hold the property names.
- followed by keyword in
- then the object.
- Then in the block, put in your statements that execute on each iteration.
Example:
const user = { name: 'Joey', gender: 'male', age: 22 };
for (const prop in user) {
console.log(`This user's ${prop} is ${user[prop]}.`);
}
- In the above example there is an object named user that has properties for name, gender, and age.
- In the for...in loop, the parentheses contain a variable named prop to hold the property name. Following that is the keyword in and the variable that's holding the object.
- For each property we log some text to the console that includes the property name and value.
- When executed it logs:
This user's name is Joey.
This user's gender is male.
This user's age is 22.
Conclusion
The topics in this tutorial correspond with the JavaScript CheatSheet Loops category. Make sure you understand each topic so you can refer back to the CheatSheet when working on your own projects.If you have the CheatSheet desktop app and downloaded the JavaScript CheatSheet, then go through the flashcards for this category to the point where you can answer them all in order and shuffled.