Search code examples
javascripthtmlecmascript-6ecmascript-5

Why JS lables does'nt work when not used with loops


I wrote a small JS Code here. Which runs without any errors

repeat:
  while(true){
    console.log('Start');
    break repeat;
    console.log('End');
  }

But when i don't use the while statement the program throws an error Undefined label repeat

repeat:
    console.log('Start');
    break repeat;
    console.log('End');

Why the program throws that error? Are labels only made for loops?


Solution

  • Basically, it works with code blocks. And while you do not have any block to break, the code throws an error.

    repeat: {
        console.log('Start');
        break repeat;
        console.log('End');
    }