Elmor
Elmor

Reputation: 4905

Using labels in javascript

Can you explain to me how to use labels on statements that interact with break: switch, while, do, and for.

with example please.

Upvotes: 1

Views: 3026

Answers (5)

Rohìt Jíndal
Rohìt Jíndal

Reputation: 27242

label: (labelled statement) basically used with break or continue statements which helps to either break or continue the labelled statement unlike normal break statement which only breaks the immediate loop.

Let me explain with a demo for both break and continue.

Break :

let i, j;

loop1:
for (i = 0; i < 3; i++) {
  loop2:
  for (j = 0; j < 3; j++) {
    if (i === 1 && j === 1) {
        break loop1; // terminate the whole loop labelled as loop1 unline normal break which will only terminate the current loop)
    }
    console.log('i = ' + i + ', j = ' + j);
  }
}

Continue :

let str = '';

loop1:
for (let i = 0; i < 5; i++) {
  if (i === 1) {
    continue loop1; // This statement will again run the loop labelled as loop1
  }
  str = str + i;
}

console.log(str); // '0234'

Upvotes: 0

Joseph
Joseph

Reputation: 119887

Commonly, I see it in breaking out to outer loops:

var i, j;

dance: for (i = 0; i < 20; i++) {
    for (j = 0; j < 20; j++) {
        console.log(i+'-'+j);
        if (j === 10) { //normally, break only breaks the immediate loop
            break dance; //this one breaks the loop labelled as dance
        }
    }
}​

//continue here after i = 0,j = 10

Upvotes: 10

Alnitak
Alnitak

Reputation: 340055

Quouting the Mozilla Developer Network Language Reference:

Provides a statement with an identifier that you can refer to using a break or continue statement.

For example, you can use a label to identify a loop, and then use the break or continue statements to indicate whether a program should interrupt the loop or continue its execution.

Note that they also say:

Labels are not very commonly used in JavaScript since they make programs harder to read an understand. As much as possible, avoid using labels and, depending on the cases, prefer calling functions or throwing an error

Upvotes: 1

Chris Gessler
Chris Gessler

Reputation: 23123

Here's a good article on the GOTO label in JS. I don't ever use GOTO label logic, so I actually learned something new today as well.

JS code from the article:

var pastures = getPastures();
 var i, pastureLen = pastures.length;

pastureLoop:
 for (i = 0; i < pastureLen; i++)
 {
    var pasture = pastures[i];
    var cows = pasture.getCows();

   var j, numCows = cows.length;
    for (j = 0; j < numCows; j++)
    {
       var cow = cows[j];
       if (cow.isEating())
          { continue pastureLoop; }
    }

   // No cows were eating, so fire the callback for pasture[i]
    pasture.executeCallback();    // or whatever
 }

Upvotes: 1

lanzz
lanzz

Reputation: 43208

Do not use labels.

Example:

// no label
while (condition) {
    // do something
}

Upvotes: 0

Related Questions