Is it better to return `undefined` or `null` from a javascript function?
I have a function which I have written which basically looks like this:
function getNextCard(searchTerms) {
// Setup Some Variables
// Do a bunch of logic to pick the next card based on termed passed through what I'll call here as 'searchTerms' all of this logic is omitted because it's not important for my question.
// ...
// If we find a next card to give, than give it
if (nextCardFound)
return nextCardFound;
// Otherwise - I'm returning undefined
return undefined;
}
Question: Would it be better to return "null" here?
I can pass whatever I want back - obviously... I just wasn't sure what is the best thing to use.
The code that calls this function knows how to deal with undefined (it actually won't ever really happen unless something goes horribly wrong)
The reason I'm asking this question is that I heard somewhere something that sounded like "Don't assign undefined to variables" or something - that it will make it harder to debug. So, the fact that I can see that null
gets passed back tells me that the return is working - but basically function similar to undefined
.
Documentation:
Mozilla Docs Didn't answer my question... google didn't either :\
This SO Question - was way too broad for what I'm trying to figure out here.
Undefined typically refers to something which has not yet been assigned a value (yet). Null refers to something which definitively has no value. In that case, I would recommend returning a null. Note that a function with no specified return value implicitly returns undefined.
From the ECMAScript2015 spec
4.3.10 undefined value
primitive value used when a variable has not been assigned a value
4.3.12 null value
primitive value that represents the intentional absence of any object value
http://www.ecma-international.org/ecma-262/6.0/#sec-terms-and-definitions-undefined-type
Further reading:
When is null or undefined used in JavaScript?
I will give you my personal opinionated way of choosing between the two.
My simple question is: could the value, given another input/state/context be defined to something?
If the answer is yes then use null
else use undefined
. More generally any function returning an object should return null
when the intended object does not exist. Because it could exist given another input/state/context.
null
represents the absence of value for a given input/state/context. It implicitly means that the concept of the value itself exist in the context of your application but may be absent.
In your example the concept of a next card exists but the card itself may not exist. null
should be used.
undefined
implicitly represents the absence of meaning of that value in your application's context. For example, if I manipulate a user
object with a given set of properties and I try to access the property pikatchu
. The value of this property should be set to undefined
because in my context it doesn't make any sense to have such a property.