Can continuation and break labels go to other statements?

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

Now I understand that I can label any block of code or statement to have a label. I can attach this shortcut to a break or continue declaration and it will jump to that line of code. But it looks like from the W3 tutorial I can only go to the top of the code block where the label is.

It seems pointless for the continue statement to have a shortcut to continue it when it can only be used inside a loop, and whatever it can do with a label can also be done with break and a label. In this example, the operator of break, used to go to the top of the operator unit; is there any difference in using continuation vs break?

I understand that this might be bad practice due to the fact that it is known as "spaghetti code", but I am a curious person.

+3


source to share


2 answers


A break foo;

does not "jump to the beginning of a statement block" - it is not a GOTO.

Rather, the name provided tells JavaScript which loop to break, which is sometimes (though perhaps rarely) useful for nested loops.

Consider this code that ends with:

outer: while (true) {
    inner: while (true) {
        break outer; // goes from here -->
    }
}
// <-- to here

      



And a [modified] variation that loops before forcibly:

outer: while (true) {
    inner: while (true) {
        // break; or,
        break inner; // goes from here -->
    }
    // <-- to here
}

      

On the other hand, it continue

just skips the rest of the code in the loop - the post actions are executed and the loop condition is overridden. That is, it continue

does not lead to the unconditional end of the cycle.

0


source


continue

ends the current iteration and goes straight to the next iteration in the loop, so mostly at the top of the code block in the loop if there is a next iteration.

break

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



So that's a pretty 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

either have break

an outer for loop if it has a label. This does not mean that you are going to the label, it just means that you are applying break

either continue

to the cycle indicated by the label, instead of the inner level loop you are currently in. However, you should still be inside this flagged statement. You cannot go to another part of the program.

What you are asking for is basically an operator goto

. To do this, perhaps you would like to read this question: How can I use goto in Javascript?

+4


source







All Articles