For…in Loop - Object Loop, Break & Continue
What is For...in Loop?
- Used to iterate over objects
- It loops through keys (properties) of an object
Key Idea
- Works mainly with objects
- Returns keys, not values directly
- Can be used with arrays, but not recommended
What is an Object?
- A collection of key-value pairs
Example:
let user = {
name: "anil",
age: 29,
email: "anil@sidhu.com",
admin: true
};
name,age→ keys"anil",29→ values
Syntax
for (let key in object) {
// code
}
Example 1: Print Keys
for (let key in user) {
console.log(key);
}
Output:
name
age
email
admin
Example 2: Print Values
for (let key in user) {
console.log(user[key]);
}
Example 3: Key + Value
for (let key in user) {
console.log(key + " is " + user[key]);
}
Output:
name is anil
age is 29
email is anil@sidhu.com
admin is true
Break in For...in
for (let key in user) {
if (key == "age") {
break;
}
console.log(key);
}
Stops loop when key is "age"
Continue in For...in
for (let key in user) {
if (key == "age") {
continue;
}
console.log(key + " is " + user[key]);
}
Skips "age" and prints others
Common Mistakes
Mistake 1: Expecting Values Directly
for (let key in user) {
console.log(key); // gives key, not value
}
Correct:
console.log(user[key]);
Mistake 2: Using with Arrays
- Not recommended for arrays
- Use
for...ofinstead
Mistake 3: Forgetting Bracket Notation
user.key // wrong
user[key] // correct
Key Points to Remember
- For...in is used for objects
- Returns keys
- Use
object[key]to get value - Supports break and continue