Can I use continue and break in Javascript for...in and for...of loops?
Asked Answered
C

1

39

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;
  }
}
Carn answered 1/7, 2019 at 8:41 Comment(7)
Yes? Why wouldn't you be able to?Croix
Why don't you try it yourself? Add a debugger or console log inside the conditionsBanquer
@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?Croix
@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!Carn
@Persijn It's not about simplicity. A user with 125+ questions asking "Debug this for me" when they can easily do it themselvesBanquer
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.Wrongheaded
@Wrongheaded that's a fair point.Banquer
F
45

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.)

Farnham answered 1/7, 2019 at 8:44 Comment(7)
There probably is a way to get the same behavior in forEach. That could be another good question.Wrongheaded
I would argue that forEach is not really a loop, but a function with a callback argument. Also, break is not restricted to loops but to all blocks (MDN link), which is a difference it has with continueRotate
Not all blocks - just loops and switches.Farnham
... and labelled blocks.Stereophonic
Oh yes, those too @Teemu.Farnham
@Wrongheaded there are already questions about break and continue in forEach...Clarita
In forEach you can use return if a condition is not met. Though it's not very idiomatic.Systaltic

© 2022 - 2024 — McMap. All rights reserved.