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