Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Searching Without for...else

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 (and while...else) runs the else only when the loop ends without break. JavaScript loops have no else: written after a loop’s closing brace, it’s a SyntaxError, and JavaScript rejects the whole file before running a line. In JavaScript, else belongs only to if.
  • 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 answers true for. The function is usually an arrow function, like (trip) => trip.canceled, much as you’d pass lambda trip: trip["canceled"] in Python.
  • When nothing matches, .find() returns undefined, JavaScript’s empty value. It doesn’t throw an error, so you check for it with an ordinary if...else. Python’s closest match is next((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. !found is JavaScript’s not found.
  • break leaves 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 reaching return, and a JavaScript function with no return gives back undefined, as Python’s gives back None.
  • JavaScript can also put a label, a name and a colon, in front of the outer loop, and break with 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():

Language: JavaScript
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");
}

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

00:01 In this lesson, you’ll port a search that ends in Python’s for…else, and see what JavaScript developers write instead. The report’s next section names the first canceled trip on N3, last night’s busiest route.

00:16 The Python script keeps N3’s trips in a list. The loop checks each trip in turn and stops at the first canceled one. The else lines up with the for, so it belongs to the loop.

00:30 It runs only when the loop finishes without a break, so that’s where “searched and didn’t find it” goes. Run it, and Python prints the trip that should have left at ten past midnight.

00:43 In the JavaScript port, each trip becomes an object, so you read its properties with a dot. The loop is the for…of you know. That leaves the else. Coming from Python, you’d attach it after the loop’s closing brace.

01:00 When Node runs this file, does the canceled trip print before Node reaches the else? Your turn: pause the video and predict.

01:13 No. Node rejects the whole file: SyntaxError, unexpected token else.

01:21 It reads the file through before running a line, as Python does. In JavaScript, else belongs only to an if statement. The brace before it ends the whole loop, and else can’t start a statement of its own.

01:38 When a loop only searches, JavaScript developers ask the array instead, with its find method. You hand it an arrow function, JavaScript’s compact function, much like a Python lambda.

01:51 This one takes a trip and returns its canceled property. Find calls the function on each trip in turn and returns the first trip it answers true for: the ten past midnight trip.

02:04 But what if nothing matches? Say the ten past midnight trip ran after all. What does find return now? Your turn: pause the video and predict.

02:21 It returns undefined, JavaScript’s empty value for “nothing here”.

02:27 There’s no error, so checking is up to you, with an ordinary if and else. The test fails, so the else prints the same line that Python’s loop else prints.

02:39 Back to last night’s real trips. If N3 had no cancellations, the report would name the next route’s first one instead, so the script searches route by route, busiest first.

02:52 Route N26 lost a trip too.

02:56 The outer loop takes one route at a time. The inner loop walks that route’s trips. A break leaves only the inner loop, as in Python, so the outer loop would move on to N26 and report a second trip.

03:11 So the Python script sets a found flag. It stops the outer loop, and afterward it says whether anything was found. The flag ports to JavaScript line for line, with an exclamation mark for not.

03:26 JavaScript can also label the outer loop, with a name and a colon. Then break search, from the inner loop, leaves both loops. The outer break drops out, the flag stays for the not-found line, and Node prints one trip, like Python.

03:44 Labels are rare, though: many JavaScript codebases return from a function instead, as in Python.

03:52 You’ve ported the report’s search. So here’s the rule: JavaScript loops have no else clause. To search an array, call find, and check for undefined when nothing matches.

04:05 To know afterward whether a loop found anything, keep a found flag. To leave nested loops, label the outer loop, or return from a function.

04:17 Next up is Looping With Positions Using entries(), a text lesson. There, you’ll number the report’s lines the way enumerate does in Python.

Become a Member to join the conversation.