ECMA-262: Breaking Out of Nested Loop Control Structures

PHP: Optional Numeric Argument for break

My first dynamic language was PHP and with that came the break statement which ends the execution of a control structure (e.g. for, while or case). It also “accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of.” This optional argument is beneficial when there are nested loops that need to be terminated prematurely without adding extra logic and without halting the entire script execution (e.g. exit).

In the following example the second/nested for loop will be terminated during the first iteration, but the outer-most loop will execute tens times.

…but in the next example it will break out of both for loops resulting in $i never incrementing from 0 to 1.

JS/AS: LabelledStatement (TL;DR)

What about ECMAScript Languages (ECMA-262)? I struggled with the absence of this feature for languages based on the ECMA-262 standard like JavaScript and ActionScript. These languages (as far as I knew) have the break statement which works just like it does in PHP, but without the optional numeric argument. This made stopping nested control structures a PITA.

Well, maybe if I RTFM I would’ve been acquainted with the LabelledStatement Statement and saved myself the heartache. This can be observed in section 12 of the ECMA-262 Langauge Specification, Edition 5.1. Basically the syntax goes something like this:

Note “theLabelName” on lines 1 and 3. This is the bread’n’butter. All that needs to happen is to label the control structure using the standard variable naming convention and post-fix it with a semicolon (:). This becomes the “calling card” of that specific construct. Lastly, the break statement has an optional argument where the previously established label can be applied.

Further Reading

See ECMA-262 5.1 Edition ECMAScript Language Specification, §12, p86.