Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can labels with "continue" and "break" jump to other statements?

What the title says is my question. I'm new to JavaScript. I am wondering if I can use statements to jump to certain lines of code. I have looked here and here. They don't explicitly say this can be done, but I think there might be a way for it to be done.

The way I understand it now it that I can designate any block of code or statement to have a label. I can attach that label to a break or continue statement, and it will jump to that line of code. But it seems, from the W3 tutorial, I can only jump to the top of the block of code where the label is.

It seems pointless to allow a continue statement to have a label proceed it when it can only be used inside of a loop and anything it can do with a label can also be done with a break and a label. In this example there is a break statement used to go to the top of the statement block; is there any difference in using the continue vs break?

I realize this could be bad practice because of what is hisorically known as "spaghetti code," but I am a curious person.

like image 586
OKGimmeMoney Avatar asked Oct 20 '25 05:10

OKGimmeMoney


1 Answers

continue ends the current iteration and jumps straight to the next iteration in the loop, so basically to the top of the code block in the loop, if there is a next iteration to do.

break ends the loop, so it jumps past it. No further iterations are performed.

So that's quite a big difference. What they have in common, is that they can have a label to indicate a specific statement. So if you have a nested for loop, you can continue or break the outer for loop if it has a label. That doesn't mean that you jump to the label, it just means that you apply the break or continue to the loop indicated by the label, instead of the inner-level loop which you are in at that moment. You still have to be inside that labeled statement, though. You cannot jump to another part of the program.

What you are asking for is basically a goto statement. For that, maybe you'd like to read this question: How can I use goto in Javascript?

like image 136
GolezTrol Avatar answered Oct 22 '25 20:10

GolezTrol