Mastering JavaScript | FOR IN LOOP
Welcome back to our "Master JavaScript" course! In this video, we'll explore one of the fundamental concepts in JavaScript: the for...in loop.
The for...in loop is a powerful tool that allows us to iterate over the properties of an object. It consists of three components: key declaration, object reference, and property iteration. Let's see it in action with some examples:
1
2
3
4
5
6
7
8
9
const person = {
name: "John",
age: 30,
city: "New York",
};
for (let key in person) {
console.log(key); // Output: name, age, city
console.log(person[key]); // Output: John, 30, New York
}
In this example, we declare the `key` variable to represent each property name (key) of the `person` object. The for...in loop iterates over each property, and we can access both the property name and its corresponding value using the `key` variable.
1
2
3
4
5
6
7
8
9
const building = {
name: "Skyscraper",
floors: 50,
location: "City Center",
};
for (let key in building) {
console.log(key); // Output: name, floors, location
console.log(building[key]); // Output: Skyscraper, 50, City Center
}
In this new example, we have an object named `building` with different properties. The for...in loop allows us to access each property name (key) of the `building` object and retrieve its corresponding value dynamically.
Both the for loop and the for...in loop are essential tools in JavaScript for iterating through data and objects.