You Can Label an `if` in JavaScript

You Can Label an `if` in JavaScript • WPShout

Interesting little article over at CSS Tricks from Alex Riviere. In it, he explains that it’s possible to label “if” (and other “block type”) statements in JavaScript. I’ve never heard (or thought about) such a feature.

As Alex says, it’s also a feature that I feel like I won’t use much, because it’s something most people neither know to be possible or will necessarily understand. (I’m always in favor of “broad comprehensibility” above “cleverness.”) But he makes the good point that for specific contexts where many-loops or ifs are not avoidable, it makes sense that these labels would make it a lot easier to track what’s happening.

This example (copied directly from his article) makes the point of their value pretty clearly to me:

let x = 0;
outerLoop:
while (x < 10) {
  x++;
  for (let y = 0; y < x; y++) {
    // This will jump back to the top of outerLoop
    if (y === 5) continue outerLoop;
    console.log(x,y);
  }
  console.log('----'); // This will only happen if x < 6
}

Obviously, real code won’t have these types of “toy conditions.” But the number of times I’ve wondered if a break or continue statement was terminating the thing I meant it to is definitely dozens, and maybe hundreds. So good to know that JavaScript offers a solution to it ?

Keep reading the article at WPShout. The article was originally written by David Hayes on 2021-05-10 15:25:05.

The article was hand-picked and curated for you by the Editorial Team of WP Archives.

Disclosure: Some of the links in this post are "affiliate links." This means if you click on the link and purchase the product, We may receive an affiliate commission.

Leave a Comment

Your email address will not be published. Required fields are marked *

Show Your ❤️ Love! Like Us
Scroll to Top