Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
  }
}
like image 548
cbdeveloper Avatar asked Jul 01 '19 08:07

cbdeveloper


People also ask

Can you use continue and break in for loops?

The break statement is usually used with the switch statement, and it can also use it within the while loop, do-while loop, or the for-loop. The continue statement is not used with the switch statement, but it can be used within the while loop, do-while loop, or for-loop.

Can you use continue in a for in loop Javascript?

The continue statement breaks one iteration (in the loop) if a specified condition occurs, and continues with the next iteration in the loop. The difference between continue and the break statement, is instead of "jumping out" of a loop, the continue statement "jumps over" one iteration in the loop.

Can you use break in a for loop Javascript?

A for..in loop can't use break.

How break and continue in for loop in Javascript?

Syntax: break labelname; continue labelname; The continue statement (with or without a label reference) can only be used to skip one loop iteration.


1 Answers

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

like image 110
Jack Bashford Avatar answered Sep 28 '22 00:09

Jack Bashford