/

JavaScript Labeled Statements: A Hidden Gem

JavaScript Labeled Statements: A Hidden Gem

Tags: JavaScript, labeled statements, Svelte, statement block, break statement

In the world of JavaScript, there is a little-known feature that many developers overlook: labeled statements. It’s a powerful tool that can enhance your code in various ways, yet it remains relatively obscure.

Recently, I came across the use of labeled statements in Svelte. They are utilized to enable reactive declarations, which are recomputed whenever the variables declared within the statement change. Take a look at this example:

1
$: console.log(variable)

With this syntax, the labeled statement $ is assigned to a statement block. This allows for complex computations and side effects within the block itself:

1
2
3
4
5
$: {
console.log(variable)
console.log('another thing')
//...
}

While this may seem unconventional, it is completely valid JavaScript code. In the case of Svelte, the compiler leverages this feature to power reactive declarations.

Despite its potential, labeled statements are rarely used outside of such frameworks. However, their primary use case is breaking out of a statement that is not the nearest enclosing loop or switch.

To illustrate this, consider the following example:

1
2
3
4
5
6
7
8
9
10
11
12
13
for (let y = 0; y < 3; y++) {
switch (y) {
case 0:
console.log(0)
break
case 1:
console.log(1)
break
case 2:
console.log(2)
break
}
}

In this case, the code will output 0 1 2 to the console, which is expected behavior.

But what if we want to break out of the for loop when we encounter case 1? Here’s how labeled statements come to the rescue:

1
2
3
4
5
6
7
8
9
10
11
12
13
loop: for (let y = 0; y < 3; y++) {
switch (y) {
case 0:
console.log(0)
break
case 1:
console.log(1)
break loop
case 2:
console.log(2)
break
}
}

Now, the output will be 0 1.

In summary, labeled statements in JavaScript open up new possibilities for controlling the execution flow of your code. While they may not be widely used, they can be a valuable tool in certain situations.