How can I use goto statement in JavaScript?

If you are familiar with core JavaScript then you must know that there is no keyword like goto in JavaScript. So in this JavaScript tutorial, I will show you how to achieve the same thing you can get with the goto statement.
In other programming languages, you have seen that there is a goto statement. But in JavaScript, we are not introduced to anything like that.
Another alternative way to achieve the same is to use the tail calls. But unfortunately, we don’t have anything like that in JavaScript.
So generally, the goto is accomplished in JS using the below two keywords.
- break
- continue
How to use goto statement in JavaScript
Let’s take the below example,
var number = 0; Start_Position document.write("Anything you want to print"); number++; if(number < 100) goto start_position;
This is not a code. Just an example where you want to use goto statement.
Now I will show you how to achieve this in JavaScript
var number = 0; start_position: while(true) { document.write("Anything you want to print"); number++; if(number < 100) continue start_position; break; }
So using continue and break you can achieve the same.
Now I am going to show you another easy example of how to use these break and continue in JavaScript
var i; for(i=1;i<=10;i++){ console.log(i); }
The output will be:
1 2 3 4 5 6 7 8 9 10
Break keyword in JavaScript
Now if we want to get out of the loop for a certain condition then we can use break keyword.
Take the above example and add break into it for a certain condition.
var i; for(i=1;i<=10;i++){ document.write(i); if(i===6){ break; } } document.write("<br>I am broken");
Now the output will be like this one:
123456 I am broken
Here we just used the break keyword to get out of the loop.
Guess The Number Game Using Java with Source Code
3D Photo/Image Gallery (on space) Using HTML5 CSS JS
Understand Continue Keyword in JavaScript
Now again take the above example and add continue statement.
var i; for(i=1;i<=10;i++){ if (i===4 || i===2) { continue; } document.write(i); if(i===6){ break; } } document.write("<br>I am broken");
Now the output will be like this one:
1356 I am broken
Here the continue keyword is used to skip rest of the code inside the loop.
So the browser will skip printing the value of variable i, if the value is equal to 4 and 2.
You may also read,
Evolution of JavaScript – JavaScript is gaining popularity Day by Day
Leave a Reply