Labeled statements - the forgotten JS feature

0x96f

Filip

Posted on September 21, 2023

Labeled statements - the forgotten JS feature

For years I have been following Svelte but never got around to trying it out. Recently I found some free time, so I decided to look into it. While going through the docs I found an interesting JS feature that I have forgotten about:

$: doubled = count * 2;
Enter fullscreen mode Exit fullscreen mode

This feature is used in Svelte to power reactive declarations, which are re-computed whenever the variables declared into the statement change. In the case above doubled will be re-computed whenever count changes.

What are labeled statements?

Lets take a step back. What is a labeled statement? According to MDN:

A labeled statement is any statement that is prefixed with an identifier. You can jump to this label using a break or continue statement nested within the labeled statement.
Enter fullscreen mode Exit fullscreen mode

Basically it is sort of a goto statement for loops. For example if we want to exit a nested loop we can use it in the following way:

loopX: for (let i = 1; i < 10; i++) {
  for (let j = 1; j < 10; j++) {
    if (i + j === 5) {
      break loopX;
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

In this example we can exit the parent loop from the child loop by just using the break statement with the label that we want to break on.

Labeled statements are not just exclusive to loops, they can also be used with if statements:

outerIf: if (count < 10) {
  if (true) {
    break outerIf;
  }
  // This will not log
  console.log(count);
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

It’s rare that you will need to use a JavaScript label. In fact, you can lead a very fulfilling career without ever knowing that this exists. However, you are now able to apply it if you happen to come across a situation where it is useful.

💖 💪 🙅 🚩
0x96f
Filip

Posted on September 21, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related