JavaScript Introducing ES2015 Objects and New Collection Types For...Of

Harsh Khandelwal
Harsh Khandelwal
5,539 Points

Why is the break keyword illegal statement error when I try to write break in the if condition of the forEach code?

teachers.forEach(teacher => {
  console.log(teacher.name);
  if (teacher.name === 'Nick') {  
    console.log(teacher.rating);
  break;
  }
});

break;
^^^^^
SyntaxError: Illegal break statement

christopher abramson
christopher abramson
22,740 Points

I don't believe you can use forEach like that. If you want to achieve the same result with a break you could use a

Switch

or if you want to do it without a break you could use a

While loop.

Mark Casavantes
Mark Casavantes
Pro Student 13,401 Points

Hello Harsh,

It would be helpful to print out all your code when you have a question.

From what I can see I would try switching => to >=.

http://www.w3schools.com/js/js_comparisons.asp

I hope this is helpful.

formatted code

1 Answer