How do I FirstOrDefault in Javascript?

Would you like to find the first item in a list that satisfies a condition? And if none of the items satisfies the condition return null? Javascript has the find-function for this. This example shows how to use it and how to interpret the result if the result is nothing.

The javascript find function returns either The first item that satisfies the condition or undefined. This means that it behaves like a FirstOrUndefined function.

Consider this list with names:

let names = ["vera", "chuck", "dave"];

Here’s the code where two items match the condition. The first one will be returned:

console.log(names.find(x => x.length === 4));

result:

vera

Here’s the code where none of the items match the condition. undefined will be returned:

console.log(names.find(x => x === "ringo"));

result:

undefined

This might be interesting to you, especially if you are used to typing C# code, where the result for nothing-found is null. Checking for null does not work when checking the result for find in Javascript.

Check the result

Here’s the same list and a new variable vera that points to one of the items:

let names = ["vera", "chuck", "dave"];
let vera = names.find(x => x === "vera");

You can check for vera !== undefined like this:

if (vera !== undefined) {
  console.log('found vera');
}

or since undefined is a falsy value, you can omit the !== undefined part

if (vera) {
  console.log('found vera');
}
Grüsse aus Berlin!
This is a cookie free and popup free website.
Join me in making the web enjoyable again by removing the need for annoying cookie warnings and silly newsletter overlays!