DEV Community

JS Bits Bill
JS Bits Bill

Posted on • Updated on

What's a JavaScript Statement Label?

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 💀
*/
Enter fullscreen mode Exit fullscreen mode

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 "🍎"
*/
Enter fullscreen mode Exit fullscreen mode

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 "🍎"
*/
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (0)