You Can Label an `if` in JavaScript

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 🤓


Add a Comment

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