36

Can I use the break and continue statements inside the for...in and for...of type of loops? Or are they only accessible inside regular for loops.

Example:

myObject = { 
  propA: 'foo', 
  propB: 'bar'
};

for (let propName in myObject) {
  if (propName !== 'propA') {
    continue;
  }
  else if (propName === 'propA') {
    break;
  }
}
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
cbdeveloper
  • 27,898
  • 37
  • 155
  • 336
  • Yes? Why wouldn't you be able to? – VLAZ Jul 01 '19 at 08:44
  • 3
    Why don't you try it yourself? Add a debugger or console log inside the conditions – adiga Jul 01 '19 at 08:44
  • 2
    @Persijn lack of research. It's *too* simple - just running the code already present with a minor alteration (add a log statement) reveals the answer. Not to mention the *thousands* of other resources online. If the question was "can I use a different name than `propName` in my code", would you still say it's a good question? – VLAZ Jul 01 '19 at 08:50
  • @Persijn Thanks. I was wondering the same thing. Two close votes on "unclear what you're asking for". How can this question not be clear? I know I could test this myself. But before testing, I searched on StackOverflow trying to find the answer. And I couldn't find one. So I asked! – cbdeveloper Jul 01 '19 at 08:51
  • @Persijn It's not about simplicity. A user with 125+ questions asking "*Debug this for me*" when they can easily do it themselves – adiga Jul 01 '19 at 08:51
  • 4
    I see the question as good, since I can see other users searching for this. And i can see value in having this question on stackoverflow even if its possible to find the answer other places. – Persijn Jul 01 '19 at 08:59
  • 2
    @Persijn that's a fair point. – adiga Jul 01 '19 at 09:44

1 Answers1

41

Yep - works in all loops.

const myObject = { 
  propA: 'foo', 
  propB: 'bar'
};

for (let propName in myObject) {
  console.log(propName);
  if (propName !== 'propA') {
    continue;
  }
  else if (propName === 'propA') {
    break;
  }
}

(By loops I mean for, for...in, for...of, while and do...while, not forEach, which is actually a function defined on the Array prototype.)

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79