JavaScript Labels

Publikováno: 15.1.2019

No matter how long you’ve been a JavaScript developer, there will always be language features that you didn’t know about until you saw them in a fringe piece of code. Your reaction generally is a bit like: One of those features I see developers quizically trying to figure out is JavaScript labels, which allow you […]

The post JavaScript Labels appeared first on David Walsh Blog.

Celý článek

No matter how long you’ve been a JavaScript developer, there will always be language features that you didn’t know about until you saw them in a fringe piece of code. Your reaction generally is a bit like:

Thinking

One of those features I see developers quizically trying to figure out is JavaScript labels, which allow you to manage break and continue with JavaScript loops. Let’s have a look at them!

The basic format of a loop is {loopname}: before the loop starts:

{loopName}:
for({iterating}) {
  {actions}
}

The power of labels comes with nested loops — you can use break and continue, paired with the label name, to manage loop escaping:

function gogogo() {
  firstLoop:
  for (let outer = 0; outer < 4; outer++) {
    secondLoop:
    for (let inner = 0; inner < 5; inner++) {
      if (inner === 3) {
        // Use continue to avoid runs 4 and 5
        continue firstLoop;
      }
      console.warn(`outer: ${outer}; inner: ${inner}`);
    }
  }
}

/*
outer: 0; inner: 0
outer: 0; inner: 1
outer: 0; inner: 2
outer: 1; inner: 0
outer: 1; inner: 1
outer: 1; inner: 2
outer: 2; inner: 0
outer: 2; inner: 1
outer: 2; inner: 2
outer: 3; inner: 0
outer: 3; inner: 1
outer: 3; inner: 2
*/

Nested loops can be difficult to manage but labels make directing and escaping them easy. The next time you want to look like a smart one in the room, break out the JavaScript labels!

The post JavaScript Labels appeared first on David Walsh Blog.

Nahoru
Tento web používá k poskytování služeb a analýze návštěvnosti soubory cookie. Používáním tohoto webu s tímto souhlasíte. Další informace