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');
}

Conclusion

The javascript find function is incredibly powerful and saves you the trouble of looping though items to find an object manually.

I’ve also written about FirstOrDefault in Python and I recommend checking out how it works in that language.

Written by Loek van den Ouweland on March 12, 2019. Questions regarding this artice? You can send them to the address below.