Table of Contents
JavaScript For In and JavaScript For Of loop
Sure, let me explain the for-in and for-of loops in JavaScript, along with their syntax and examples.
for-in Loop
The for-in loop is used to iterate over the properties of an object. It enumerates the properties of an object, including inherited properties from its prototype chain.
*Syntax:*
javascript
for (variable in object) {
// code to be executed
}
- Variable: A variable that will be assigned the property name on each iteration.
- Object: The object whose enumerable properties will be iterated.
Example
javascript
let person = {
name: 'John',
age: 30,
city: 'New York'
};
for (let key in person) {
console.log(key + ': ' + person[key]);
}
In this example, the for-in loop iterates over the properties of the person object, and on each iteration, it logs the property name and its corresponding value.
for-of Loop:
The for-of loop is used to iterate over the values of an iterable object, such as an array or a string.
*Syntax:*
javascript
for (variable of iterable) {
// code to be executed
}
- Variable: A variable that will be assigned the value of each element in the iterable.
- Ahiiterable: The iterable object (e.g., array, string) to be iterated.
Example
javascript
let colors = ['red', 'green', 'blue'];
for (let color of colors) {
console.log(color);
}
In this example, the for-of loop iterates over the elements of the colors array, and on each iteration, it logs the value of the current element.
To summarize
- Use for-in to iterate over the properties of an object.
- Use for-of to iterate over the values of an iterable object like an array.