Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use case for "break Identifier" in JavaScript?

Tags:

javascript

the spec goes

BreakStatement :   
    break ;
    break [no LineTerminator here] Identifier ;

then it goes

The program contains a break statement with the optional Identifier, where Identifier does not appear in the label set of an enclosing (but not crossing function boundaries) Statement.

...

A BreakStatement with an Identifier is evaluated as follows:

Return (break, empty, Identifier).

What on bloody earth does this mean?

like image 303
Trident D'Gao Avatar asked Dec 18 '15 22:12

Trident D'Gao


2 Answers

A label is something like this:

// ...
mylabel:
// ...

This can be placed anywhere as a statement.

It is useful to break/continue when having multiple nested for loops.

An example of its usage:

var i, j;

loop1:
for (i = 0; i < 3; i++) {      //The first for statement is labeled "loop1"
   loop2:
   for (j = 0; j < 3; j++) {   //The second for statement is labeled "loop2"
      if (i === 1 && j === 1) {
         continue loop1;
      }
      console.log("i = " + i + ", j = " + j);
   }
}

// Output is:
//   "i = 0, j = 0"
//   "i = 0, j = 1"
//   "i = 0, j = 2"
//   "i = 1, j = 0"
//   "i = 2, j = 0"
//   "i = 2, j = 1"
//   "i = 2, j = 2"
// Notice how it skips both "i = 1, j = 1" and "i = 1, j = 2"

Source.

like image 151
Louay Alakkad Avatar answered Oct 17 '22 17:10

Louay Alakkad


If you look on MDN, there's examples

outer_block: {
    inner_block: {
        console.log('1');
        break outer_block; // breaks out of both inner_block and outer_block
        console.log(':-('); // skipped
    }
    console.log('2'); // skipped
}

as you can see, you can break with an identifier that selects a label higher up in the chain than just the first immediate parent statement.

The default action without an identifier would be

outer_block: {
    inner_block: {
        console.log('1');
        break; // breaks out of the inner_block only
        console.log(':-('); // skipped
    }
    console.log('2'); // still executed, does not break
}

The break has to be inside the label, you can't break labels based on indentifiers that the break is outside of.

like image 44
adeneo Avatar answered Oct 17 '22 17:10

adeneo