Here is the basic syntax for a for...of
loop:
for (variable of iterable) {
// code block to be executed
}
The variable in the example represents the current value of the iterable that is being looped over.
If you have an array of numbers, the variable would be the current number in the array. If you have a string, the variable would be the current character in the string.
Let’s take a look at a few examples so you can better understand how the for...of
loop works.
In this first example we have an array of numbers and we want to loop over each number and log it to the console.
const numbers = [1, 2, 3, 4, 5];
for (const num of numbers) {
console.log(num);// 1, 2, 3, 4, 5 iterated
}
We have created a variable called num
that will represent the current number in the array. For iteration 1, num
will be 1
, for iteration 2, num
will be 2
, and so on.
Inside the loop, we are logging the current number to the console.
Here is another example where we have a string and we want to loop over each character and log it to the console.
const str = 'freeCodeCamp';
for (let char of str) {
console.log(char); // f r e e c o d e c a m p
}
In this example, we have created a variable called char
that will represent the current character in the string.
For each iteration, the loop will log the current character to the console.
It is important to note that you can use let
, or const
when declaring the variable in a for...of
loop.
If you are going to use const
though, make sure that the value of the variable does not change inside the loop. If it does, you will get an error.
Here is an example of using const
that results in an error:
const numbers = [1, 2, 3, 4, 5];
for (const num of numbers) {
console.log(num);
num = num + 1; // This will cause an error
}
In this example, we are trying to change the value of num
inside the loop. Since we declared num
with const
, we will get an error. So, if you need to change the value of the variable inside the loop, use let
instead.
Let’s take a look at one last example dealing with an array of objects.
const people = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 },
{ name: 'Jim', age: 40 }
];
for (const person of people) {
console.log(`${person.name} is ${person.age} years old`);
}
//John is 30 years old
//Jane is 25 years old
//Jim is 40 years old
In this example, we have an array of objects called people
. Each object has a name
and age
property.
When we loop through the array, we create a variable called person
that will represent the current object in the array.
Inside the loop, we are outputting a message to the console.
The first message will be John is 30 years old
, the second message will be Jane is 25 years old
, and the third message will be Jim is 40 years old
.
for...of
loops are really useful when you need to loop over values from an iterable like an array or a string. They are also easy to read and can make your code more concise.