Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

GodziLaravel's avatar

How to return null instead of undefined using .find()

Hello

console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found

In this example if there is no results it will returns undefined But is it possible to return Null instead ?

Thanks

0 likes
3 replies
tykus's avatar
tykus
Best Answer
Level 104

As far a I know, you can't do anything inside the callback to force a result other than undefined whenever nothing is found, so you would need to use Short Circuit Evaluation to get something other than undefined

console.log([4, 6, 8, 12].find(isPrime) || null)
1 like
tykus's avatar

@godzilaravel be aware that this approach will work for the given example - but if your find test was different and an item is found within the array which is falsey (null, false, 0, ...) then it produce null as the result everytime. This is not the case for an isPrime test, but could be for an isEven test:

[0, 1, 2, 3].find((num) => num % 2 === 0) || null // result is null, not 0!

Please or to participate in this conversation.