Here’s a basic example of break in use: const x = 1 īreak // Doesn't check the rest of the switch statement if 1 is trueīreak // Doesn't check the rest of the switch statement if 2 is trueīreak // Doesn't check the rest of the switch statement if 3 is true It’s a great way to escape out of a conditional statement or end a loop early. It is most commonly used in a switch statement to end a case, but it can also be used to end an if statement early, or also to cause a for or while loop to end and stop looping. A break statement will terminate the currently running loop or conditional statement. Let’s back up a bit and talk about break and continue. The use cases for labels are limited, but incredibly powerful in the right hands. ![]() They also do not conflict with variable names, so if you really want to confuse people, you can have a loop and a variable be the same name! Please don’t do this - future you, and anyone else that has to read your code will appreciate it. ![]() Labels are only an internal reference to a statement and are not something that can be looked up, exported, or stored in a value. Here’s the basic syntax for a label: let x = 0 To apply a label to a statement, start the statement with label: and whatever you put as “label” will be the label you can reference later. That allows you to break or continue the labeled statement from within. Typically: loops and conditional statements. But, as we’ll see, labels can be useful in very specific instances.īut first: A JavaScript label should not be confused with an HTML, which is a completely different thing!Ī JavaScript label is a way to name a statement or a block of code. They aren’t new! I don’t think all that many people know about them and I’d even argue they are a bit confusing. Labels are a feature that have existed since the creation of JavaScript.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |