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;
  }
}
7
  • Yes? Why wouldn't you be able to?
    – VLAZ
    Commented Jul 1, 2019 at 8:44
  • 3
    Why don't you try it yourself? Add a debugger or console log inside the conditions
    – adiga
    Commented Jul 1, 2019 at 8: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
    Commented Jul 1, 2019 at 8:50
  • 5
    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
    Commented Jul 1, 2019 at 8:59
  • 2
    @Persijn that's a fair point.
    – adiga
    Commented Jul 1, 2019 at 9:44

1 Answer 1

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

7
  • There probably is a way to get the same behavior in forEach. That could be another good question.
    – Persijn
    Commented Jul 1, 2019 at 8:47
  • 1
    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 continue
    – Kaddath
    Commented Jul 1, 2019 at 8:49
  • 2
    Not all blocks - just loops and switches. Commented Jul 1, 2019 at 8:50
  • 2
    ... and labelled blocks.
    – Teemu
    Commented Jul 1, 2019 at 8:52
  • Oh yes, those too @Teemu. Commented Jul 1, 2019 at 8:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.