DEV Community

Akanksha
Akanksha

Posted on

Illegal Use of Break Statement Error in JavaScript

Have you wondered, why we get Illegal use of break statement error in JavaScript?
While using loops in JavaScript, you might have got stuck because of this error. In this blog, we will discuss why we get this error.

Loops
A loop is a sequence of instructions that is continuously repeated until a certain condition is reached. They are used if we want to perform a task 'n' number of times.
There are different kinds of loops we can use, such as for loop, while loop, do-while loop, forEach loop, etc.

Break Statement
The break statement is a loop control statement that is used to terminate the loop. As soon as the break statement is encountered, the loop is terminated and the control comes out of the loop, to execute the immediately next statement after the loop.
Syntax: break;

Now, lets see when do we get Illegal use of break statement error. Lets take an example:

if(year2 > 1){
            date2 = date2 - 1;
            if(date2 < 1){
                month2 = month2 - 1;        
                if(month2 < 1){
                    month2 = 12;
                    year2 = year2 - 1;      
                    if(year2 < 1){
                        break;
                    }
                    date2 = datesInMonth[month2 - 1];
                }
            }
Enter fullscreen mode Exit fullscreen mode

For the above example, we will get the error Illegal use of break statement. That is because, break statement is used to break out of a loop like for, while, do-while, etc. But here, we do not have a loop, we are using if statement, which is a conditional statement.

So, in this case, we need to use return statement to break the execution flow of the current function and return to the calling function.

if(year2 > 1){
            date2 = date2 - 1;
            if(date2 < 1){
                month2 = month2 - 1;        
                if(month2 < 1){
                    month2 = 12;
                    year2 = year2 - 1;      
                    if(year2 < 1){
                       return;
                    }
                    date2 = datesInMonth[month2 - 1];
                }
            }
Enter fullscreen mode Exit fullscreen mode

Now, the error is solved and our program will execute properly.

I hope you found this helpful!!!

Top comments (0)