:: krowemoh

Saturday | 28 DEC 2024
Posts Links Other About Now

previous
next

Javascript Loop Labels

2022-01-22

TIL! You can have loop labels so that you can break and continue by naming the loop you want to do an action on. You can also break out of code blocks by giving them labels. That part seems more dangerous as now you have weird control flow I imagine. There probably should be a really good reason to use labels and likely a better way to structure the code so you don't need labels.

https://stackoverflow.com/questions/183161/whats-the-best-way-to-break-from-nested-loops-in-javascript

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label

http://blog.marcinchwedczuk.pl/break-out-of-code-block-in-java-and-javascript

loop1:
for (let episode of episodes) {
    loop2:
    for (let url of episode.urls) {
        if (fs.existsSync(episode.name) {
            break loop1;
        }
        download(episode);
    }
}

This way I can check if an episode already exists and break out of the first loop completely. This is pretty cool and I can see it being useful in some instances. I also think it is pretty readable so it doesn't look like it would be a bad practice.

This is a contrived example as I can move that if statement before the second loop which would result in simpler logic. This is definitely cool though!