feat(curriculum): Add interactive examples to What Is the For...in Loop, and When Should You Use It (#63337)

This commit is contained in:
Clarence Bakosi 2025-10-31 10:15:58 +01:00 committed by GitHub
parent d94cec7a3e
commit 489a87874f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -5,7 +5,7 @@ challengeType: 19
dashedName: what-is-the-for-in-loop-and-when-should-you-use-it
---
# --description--
# --interactive--
A `for...in` loop is best used when you need to loop over the properties of an object. This loop will iterate over all enumerable properties of an object, including inherited properties and non-numeric properties.
@ -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 a `fruit` object and we want to loop over each property and log the value to the console.
:::interactive_editor
```js
const fruit = {
name: 'apple',
@ -37,6 +39,8 @@ for (const prop in fruit) {
}
```
:::
The `prop` variable represents the current property of the object. `fruit[prop]` is used to access the value of each property.
For the first iteration, `prop` will be `name`. For the second iteration, `prop` will be `color`, and so on.
@ -45,6 +49,8 @@ The results logged to the console will be `apple`, `red`, and `0.99`.
In this second example, we have a nested object and we want to loop over each property and log the value to the console.
:::interactive_editor
```js
const person = {
name: 'John',
@ -61,6 +67,8 @@ for (const prop in person) {
}
```
:::
The `address` property is an object itself. The `for...in` loop will also loop over the properties of the `person` object and log the entire `address` object to the console.
Here is what the result will look like in the console:
@ -73,7 +81,19 @@ John
If you want to loop over the properties of the `address` object, you can nest another `for...in` loop inside the first one.
:::interactive_editor
```js
const person = {
name: 'John',
age: 30,
address: {
street: '123 Main St',
city: 'Anytown',
state: 'CA'
}
};
function isObject(obj) {
return typeof obj === 'object' && !Array.isArray(obj) && obj !== null;
}
@ -89,6 +109,8 @@ for (const prop in person) {
}
```
:::
In this example, we have a custom function `isObject` that checks if the value is an object.
The `Array.isArray` method is used to check if the value is an array. By placing the logical NOT operator (`!`) in front of the method, we are checking if the value is not an array.