Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

illegal use of break statement; javascript

When this variable becomes a certain amount i want the loop to stop, but i keep getting the error, "Uncaught SyntaxError: Illegal break statement".

function loop() {     if (isPlaying) {         jet1.draw();         drawAllEnemies();         requestAnimFrame(loop);         if (game==1) {              break;          }      } }  
like image 756
lehermj Avatar asked Mar 21 '14 02:03

lehermj


People also ask

Can we use break statement in JavaScript?

The break statement breaks out of a switch or a loop. In a switch, it breaks out of the switch block. This stops the execution of more code inside the switch. In in a loop, it breaks out of the loop and continues executing the code after the loop (if any).

Can we use break in for loop JavaScript?

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

What does illegal return statement mean?

The "Illegal return statement" error occurs when the return statement is used outside of a function. To solve the error make sure to only use the return statement inside of a named or an arrow function. The statement ends a function's execution and returns the value to the caller.

Can we use break and continue in JavaScript?

JavaScript Labels break labelname; continue labelname; The continue statement (with or without a label reference) can only be used to skip one loop iteration. The break statement, without a label reference, can only be used to jump out of a loop or a switch.


1 Answers

break is to break out of a loop like for, while, switch etc which you don't have here, you need to use return to break the execution flow of the current function and return to the caller.

function loop() {     if (isPlaying) {         jet1.draw();         drawAllEnemies();         requestAnimFrame(loop);         if (game == 1) {            return         }     } } 

Note: This does not cover the logic behind the if condition or when to return from the method, for that we need to have more context regarding the drawAllEnemies and requestAnimFrame method as well as how game value is updated

like image 65
Arun P Johny Avatar answered Sep 22 '22 03:09

Arun P Johny