What's a JavaScript Statement Label?

What's a JavaScript Statement Label?

ยท

2 min read

While perusing a list of JavaScript statement and declaration types, I noticed one I hadn't seen before and that was a "label."

With a label you can namespace a statement:

myLabel: {
  console.log('To be');
  break myLabel;
  console.log('Or not to be');
}

console.log('That is the question ๐Ÿ’€');

/*
Logs:

  To be
  That is the question ๐Ÿ’€
*/

We use a break to terminate the statement labeled myLabel and thus console.log('Or not to be'); does not run.

This code looks like we're creating an object with a key named myLabel and a value of another object but that is not it. As described in my earlier article, blocks are a set of zero or more statements grouped by curly braces. In our example, we've created a labeled block. Inside the block code we are breaking out of the same block referenced by its label.

Although they're not commonly used (in lieu of function calls), labels can be used with loops to either continue or jump out of the iteration:

const fruit = ['๐Ÿ‡', '๐Ÿ', '๐ŸŽ'];

myLoop:
for (let i = 0; i < 3; i++) {

  loopDaFruit:
  for (let j = 0; j < fruit.length; j++) {
    if (i === 1) break loopDaFruit;
    console.log(i, fruit[j]);
  }
}

/*
Logs:

  0 "๐Ÿ‡"
  0 "๐Ÿ"
  0 "๐ŸŽ"
  2 "๐Ÿ‡"
  2 "๐Ÿ"
  2 "๐ŸŽ"
*/

Conversely, we can achieve the same result using the first loop's label with continue:

const fruit = ['๐Ÿ‡', '๐Ÿ', '๐ŸŽ'];

myLoop:
for (let i = 0; i < 3; i++) {

  loopDaFruit:
  for (let j = 0; j < fruit.length; j++) {
    if (i === 1) continue myLoop;
    console.log(i, fruit[j]);
  }
}

/*
Logs:

  0 "๐Ÿ‡"
  0 "๐Ÿ"
  0 "๐ŸŽ"
  2 "๐Ÿ‡"
  2 "๐Ÿ"
  2 "๐ŸŽ"
*/

Seeing a labeled statement first the first time threw me off because it almost looked like some form of object literal syntax. Now it's clear what's really going on on, even though labeled statements are rare to see in the wild. ๐Ÿฆ


Check out more #JSBits at my blog, jsbits-yo.com. Or follow me on Twitter!

ย