DEV Community

JS Bits Bill
JS Bits Bill

Posted on • Edited on

4 3

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!

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay