cbdeveloper
cbdeveloper

Reputation: 31495

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

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;
  }
}

Upvotes: 41

Views: 22325

Answers (1)

Jack Bashford
Jack Bashford

Reputation: 44135

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

Upvotes: 46

Related Questions