Labeled statements - the forgotten JS feature

21 Sep 2023

Intro

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 intresting JS feature that I have forgotten about:

$: doubled = count * 2;

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.

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;
		}
	}
}

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);
}

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.