Home Courses For…in Loop - Object Loop, Break & Continue

For…in Loop - Object Loop, Break & Continue

What is For...in Loop?

  1. Used to iterate over objects
  2. It loops through keys (properties) of an object


Key Idea

  1. Works mainly with objects
  2. Returns keys, not values directly
  3. Can be used with arrays, but not recommended


What is an Object?

  1. A collection of key-value pairs

Example:


let user = {
name: "anil",
age: 29,
email: "anil@sidhu.com",
admin: true
};

  1. name, age → keys
  2. "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

  1. Not recommended for arrays
  2. Use for...of instead


Mistake 3: Forgetting Bracket Notation


user.key // wrong
user[key] // correct


Key Points to Remember

  1. For...in is used for objects
  2. Returns keys
  3. Use object[key] to get value
  4. Supports break and continue
Share this lesson: