feat(curriculum): Add interactive examples to How Does the For...of Loop Work, and When Should You Use It (#63343)

This commit is contained in:
Clarence Bakosi
2025-10-31 10:11:33 +01:00
committed by GitHub
parent f0abd7cb7b
commit 24573d2620
@@ -5,7 +5,7 @@ challengeType: 19
dashedName: how-does-the-for-of-loop-work-and-when-should-you-use-it
---
# --description--
# --interactive--
A `for...of` loop is used when you need to loop over values from an iterable. Examples of iterables would be arrays, and strings.
@@ -25,6 +25,8 @@ Let's take a look at a few examples so you can better understand how the `for...
In this first example we have an array of numbers and we want to loop over each number and log it to the console.
:::interactive_editor
```js
const numbers = [1, 2, 3, 4, 5];
@@ -33,12 +35,16 @@ for (const num of numbers) {
}
```
:::
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.
:::interactive_editor
```js
const str = 'freeCodeCamp';
@@ -47,6 +53,8 @@ for (let char of str) {
}
```
:::
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.
@@ -70,6 +78,8 @@ In this example, we are trying to change the value of `num` inside the loop. Sin
Let's take a look at one last example dealing with an array of objects.
:::interactive_editor
```js
const people = [
{ name: 'John', age: 30 },
@@ -82,6 +92,8 @@ for (const person of people) {
}
```
:::
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.