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’s
for...else(andwhile...else) runs theelseonly when the loop ends withoutbreak. JavaScript loops have noelse: written after a loop’s closing brace, it’s aSyntaxError, and JavaScript rejects the whole file before running a line. In JavaScript,elsebelongs only toif. - When a loop only searches, JavaScript developers use
.find(). It calls a function on each item in turn and returns the first item the function answerstruefor. The function is usually an arrow function, like(trip) => trip.canceled, much as you’d passlambda trip: trip["canceled"]in Python. - When nothing matches,
.find()returnsundefined, JavaScript’s empty value. It doesn’t throw an error, so you check for it with an ordinaryif...else. Python’s closest match isnext((trip for trip in trips if trip["canceled"]), None), which hands back the default you give it. - When the code after a loop needs to know whether the loop found something, keep a found flag,
as you would in Python.
!foundis JavaScript’snot found. breakleaves only the loop it’s in, as in Python. To leave nested loops, the everyday answer in both languages is a function that returns from inside both loops. Many JavaScript codebases prefer it. When nothing matches, the function ends without reachingreturn, and a JavaScript function with noreturngives backundefined, as Python’s gives backNone.- JavaScript can also put a label, a name and a colon, in front of the outer loop, and
breakwith that name from the inner loop. Labels are rare, and a label can’t be reached from inside a callback function, only from the loops themselves.
The report’s search, with .find():
const trips = [
{ departs: "23:10", canceled: false },
{ departs: "23:40", canceled: false },
{ departs: "00:10", canceled: true },
{ departs: "00:40", canceled: false },
];
const first = trips.find((trip) => trip.canceled);
if (first !== undefined) {
console.log(`Canceled: ${first.departs}`);
} else {
console.log("No canceled trips");
}