For Loops
For loops are a common control flow structure in programming that allows you to repeat a block of code a specific number of times.
In JavaScript, there are three types of for loops:
Standard For Loop
The standard for loop is the most common type of loop in JavaScript. It allows you to execute a block of code a specific number of times. Here is the syntax for a standard for loop:
for (initialization; condition; update) {
// code to be executed
}where:
- The
initializationis executed before the loop starts. It is typically used to initialize a counter variable. - The
conditionis evaluated before each iteration of the loop. If the condition is true, the code inside the loop is executed; otherwise, the loop terminates. - The
updateis executed after each iteration of the loop. It is typically used to update the counter variable.
Here is an example of using a standard for loop in JavaScript:
for (let i = 0; i < 5; i++) {
console.log(i);
}In this example, the loop will execute 5 times, and the output will be:
0
1
2
3
4
5For-In Loop
The for-in loop is used to iterate over the properties of an object. Here is the syntax for a for-in loop:
for (variable in object) {
// code to be executed
}where:
- The
variableis a string that represents the name of a property in the object. - The
objectis the object over which to iterate.
Here is an example of using a for-in loop in JavaScript:
let person = {
name: "John",
age: 30,
};
for (let key in person) {
console.log(key + ": " + person[key]);
}In this example, the loop will iterate over the properties of the person object and output:
name: John
age: 30For-Of Loop
The for-of loop is used to iterate over the elements of an iterable object (e.g., an array). Here is the syntax for a for-of loop:
for (variable of iterable) {
// code to be executed
}where:
- The
variableis a reference to the current element in the iterable. - The
iterableis the object over which to iterate.
Here is an example of using a for-of loop in JavaScript:
let colors = ["red", "green", "blue"];
for (let color of colors) {
console.log(color);
}In this example, the loop will iterate over the elements of the colors array and output:
red
green
blueConclusion
- The
standard for loopis used to execute a block of code a specific number of times. - The
for-in loopis used to iterate over the properties of an object. - The
for-of loopis used to iterate over the elements of an iterable object.
How is this guide?
Sign in to share your feedback
Help us improve by sharing your thoughts on this guide.
Last updated on