In this post, you will learn how to use a break and continue keywords as an alternative method of goto keyword. Let’s start:
How to Use the Goto in JavaScript?
The goto statement points out the location where the code execution will resume. The break and continue keywords work together to shift control from one part of the code to another part. Moreover, it can be utilized in the loop for passing control to other sections of code. Most developers adopt this method to evaluate the code or check the issues/errors in code.
Note: Developers/Users can utilize the break keyword to get out of the loop after fulfilling a certain condition.
The syntax of the above keywords is as follows.
Syntax
continue piece_of_code;
Piece_of_code: specify the variable or block of code, but it cannot be a JavaScript keyword.
Example
An example is given of how to use the break and continue to switch the control from one statement to another statement of code. The code is as follows:
Code
var x;
console.log("An example of use break and continue keyword");
for(x=1;x<=18;x++){
if (x===3 || x===4) {
continue;
}
console.log(i);
if(x===6){
break;
}
}
console.log("The execution is stopped");
The description of the above code is listed below.
- Firstly, the var x is declared
- Inside the for loop, the variable x is initialized, and the condition for the x is set to “x<=18”. Lastly, the value of x is incremented by 1.
- The keyword continue is utilized within a loop that moves the control to the next cycle of the loop.
- The break keyword is employed to stop the execution process of the code.
Output
The output returns the execution of the above code. In the display, values are presented as missing 3 and 4 due to the continue keyword. Moreover, the break keyword breaks the code after printing the value 6. In the end, a message is displayed “The execution is stopped”.
Conclusion
The goto statement does not work directly in JavaScript. To compensate for the purpose, break and continue keywords can be used as an alternative to the goto statement. We have briefly explained the working and usage of the break and continue keywords in JavaScript. Using these keywords, control is switched from one part of the code to another part of the code.