Searching Without for…else
In this lesson, you ported the night-bus report’s search for the first canceled trip from Python to JavaScript.
| Python | JavaScript |
|---|---|
for ... else: search |
.find(), then if (first !== undefined) { ... } else { ... } |
lambda trip: trip["canceled"] |
(trip) => trip.canceled |
found flag, if not found: |
found flag, if (!found) |
| return from a function inside both loops | the same, or a label on the outer loop and break with its name |
- JavaScript loops have no
else. After a loop’s closing brace, it’s aSyntaxError, and JavaScript rejects the whole file before running a line.elsebelongs only toif. - When a loop only searches, call
.find(). It returns the first item the function answerstruefor, orundefinedwhen nothing matches, with no error, so an ordinaryif...elsedoes the loopelse’s job. - When code after a loop needs to know whether it found something, keep a found flag, as in Python.
breakleaves only its own loop, as in Python. To leave nested loops, return from a function, as in Python and as many JavaScript codebases prefer. JavaScript can also label the outer loop, a name and a colon, andbreakwith that name from the inner loop. Labels are rare.
The report’s search, with .find():