DEV Community

Cover image for What are labels and how do they work
Arsenii Gorushkin
Arsenii Gorushkin

Posted on

What are labels and how do they work

Have you ever wandered what labels are in javascript? Or have you never even heard of them? In any of these cases I will introduce you to them today. In this post we will break down what are labels, and what they do.

What are labels?

Labels mean pretty much what they spell. Labels are used to identify a certain loop, and give developer the ability to conitnue or break the loop at will, which would either continue or stop the execution of the loop as you might have realized from the keywords.

How to use labels?

Label syntax is fairly simple, only things you need to know are 2 keywords, and syntax

This, down here is an example of syntax

label:
  function
Enter fullscreen mode Exit fullscreen mode

Now I will show you how to use continue and break in labels

Break

let i = 0;

label: 
for (i = 0; i < 1000000000; i ++) {
  if (i === 6) {
    break label;
  }
  console.log(i)
}
Enter fullscreen mode Exit fullscreen mode

At firs this loop might look scary, because it is iterated through thousands of times, or is it? Let's look at the output inside of the terminal

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

Hmm... Weird, isn't it? Now look inside the for loop, and the if statement where it says if 10 then break loop. If we use the break keyword, then it will completely stop the loop, and it wouldn't execute anymore.

Continue

Now, let's look at the continue keyword. Continue keyword is basically a break, but instead of stopping the whole loop, it will only stop this exact iteration from the moment you wrote continue. After stopping the rest of the loop, it will go to the next iteration of it. Let me show you an example.

let i = 0;

label:
for (i = 0; i < 5; i++) {
  if (i === 3) {
    continue label;
  }
  console.log(i)
}
Enter fullscreen mode Exit fullscreen mode

And this is what it prints out in console

0
1
2
4
Enter fullscreen mode Exit fullscreen mode

As you can see from the example, it stops the iteration, when i equals to 3, but it still starts the next iteration, and this can be used for a lot of cool tricks.

Labeled Blocks

You can also write labeled block of code, which you could stop at will as well. They do not have to be loops, but just regular old script in curly brackets. Here is an example of one

label: {
  console.log("Hello!");
  break label;
  console.log("Bad");
}
console.log("World!")

//Output: Hello World!
Enter fullscreen mode Exit fullscreen mode

This is pretty much everything you need to know about labels, and if you enjoyed, then feel to react, share, and follow, as well as leave some feedback to improve these small tutorials in future.

It was gorushkin, and cya later!

For now feel free to read my other posts

Discussion (0)