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.

Answers:

Answer

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
Answer

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
 }
Answer

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

Answer

Do not use labels.

Example:

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.