Home > database >  Implement condition in for..in loop
Implement condition in for..in loop

Time:11-07

I am looking at for..in tutorial from MDN documentation

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

The example iterates over the object's properties and prints all. I am trying to print only if value of object's property is 3. Can someone please help me understand where I am going wrong. And also if possible explain.

const object = { a: 1, b: 2, c: 3 };

for (const property in object.c == 3) {
  console.log(`${property}: ${object[property]}`);
}

CodePudding user response:

for...in loops can't have conditions.¹ You have to implement the condition as an if within the loop:

for (const property in object) {
    if (object[property] === 3) {
        console.log(`${property}: ${object[property]}`);
    }
}

I've assumed you want any property with the value 3, not just c (since there'd be no need for a loop).


¹ "for...in loops can't have conditions" So why didn't you get an error? Because your code was syntactically correct, it just didn't do what you expected.

  • Related