Skip to content

Commit 4577941

Browse files
Document the $break faux-keyword for Enumerable methods.
1 parent 1cd72a9 commit 4577941

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

src/prototype/lang/enumerable.js

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,42 @@
3030
*
3131
* If there is no `context` argument, the iterator function will execute in
3232
* the scope from which the [[Enumerable]] method itself was called.
33-
*
33+
*
34+
* ##### Flow control
35+
*
36+
* You might find yourself missing the `break` and `continue` keywords that
37+
* are available in ordinary `for` loops. If you need to break out of an
38+
* enumeration before it's done, you can throw a special object named
39+
* `$break`:
40+
*
41+
* var myObject = {};
42+
*
43+
* ['foo', 'bar', 'baz', 'thud'].each( function(name, index) {
44+
* if (name === 'baz') throw $break;
45+
* myObject[name] = index;
46+
* });
47+
*
48+
* myObject;
49+
* // -> { foo: 0, bar: 1 }
50+
*
51+
* Though we're technically throwing an exception, the `each` method knows
52+
* to catch a thrown `$break` object and treat it as a command to stop
53+
* iterating. (_Any_ exception thrown within an iterator will stop
54+
* iteration, but only `$break` will be caught and suppressed.)
55+
*
56+
* If you need `continue`-like behavior, you can simply return early from
57+
* your iterator:
58+
*
59+
* var myObject = {};
60+
*
61+
* ['foo', 'bar', 'baz', 'thud'].each( function(name, index) {
62+
* if (name === 'baz') return;
63+
* myObject[name] = index;
64+
* });
65+
*
66+
* myObject;
67+
* // -> { foo: 0, bar: 1, thud: 3 }
68+
*
3469
* ##### Mixing [[Enumerable]] into your own objects
3570
*
3671
* So, let's say you've created your very own collection-like object (say,

0 commit comments

Comments
 (0)