Is it better to return `undefined` or `null` from a javascript function?
Solution 1
I will argue there is no best way, and even standard functions sometimes choose one or the other.
For example:
-
[[Prototype]]
Ordinary objects have a [[Prototype]] internal slot, which determines from which other object they inherit from. Of course, there must be a way to say that an object does not inherit from any other one. In this case, "there is no such object" is represented using
null
. -
Object.getOwnPropertyDescriptor
It is expected to return a property descriptor, that is, an object which describes a property (e.g. value, writability, enumerability and configurability). However, the property may not exist. In this case, "there is no such property" is represented using
undefined
. -
document.getElementById
It is expected to return the element with the given ID. However, there might be no element with that ID. In this case, "there is no such element" is represented using
null
.
So just choose whatever you prefer or think makes more sense for your specific case.
Solution 2
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?
Solution 3
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.
Solution 4
Depends on what u need to do with the returned value.
typeof null returns an object. that object has a value of undefined
typeof undefined returns undefined
Solution 5
undefined
is not something you should assign to. You might want to consider to return something else other than undefined
. In your case, even if you don't return anything at all, the result will be undefined
already. So, I'd suggest to go with null
instead.
Consider this sample,
function getSomething() {
// .. do something
return undefined;
}
function doSomething() {
// .. I'm not gonna return anything.
}
var a = getSomething();
var b = doSomething();
Above sample result in a === b
, which is undefined
. The difference is that you save 1 statement execution.
Jeremy Iglehart
Updated on March 06, 2020Comments
-
Jeremy Iglehart about 4 years
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 toundefined
.
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.
-
Dan almost 8 yearsPersonally i usually use null.
-
Felix Kling almost 8 years"that object has a value of undefined" No it's not and it's not an object, it's Null.
typeof
doesn't necessarily return the true data type of a value, it has a map that maps data types to labels and returns the corresponding label. -
Oriol almost 8 yearsDon't trust
typeof
, despite its name it doesn't tell the type of a value. -
choz almost 8 years@Oriol I mean,
undefined
does not have to be assigned. All declared variable without values are alreadyundefined
. -
Oriol almost 8 yearsYes, undefined is the value used when a variable has not been assigned a value. Why exactly does that imply you shouldn't return undefined in a function?
-
Oriol almost 8 yearsBut
document.getElementById('iDoNotExist')
returnsnull
, even though the meaning is closer to "this thing isn't there at all". If standard methods do it, why not OP? -
Jeremy Iglehart almost 8 years@choz & @Oriol - as mentioned before by @chiliNUT "Note that a function with no specified return value implicitly returns undefined." - this is true because
(function(){ /* code */ })()
returns null in a console. -
choz almost 8 years@JeremyIglehart That code actually does not return anything. And else, it gives
undefined
on my chrome and firefox console. -
Oriol almost 8 yearsOK I didn't understand your point. Yes, if you don't return anything explicitly, undefined will be returned implicitly. But why does that matter?
-
chiliNUT almost 8 years@Oriol, in my mind, since a void function returns undefined, that is a reserved value for functions of that type, so that when handling the return value of a function, null tells me it decided to return null, whereas undefined tells me it either decided to return undefined, or it decided not to return anything, but I don't definitively know which. Further, if I am doing
var x=someFunc();
, I am intentionally assigning x a value, and would rather it not pass any tests which indicate it has not (or may have not) been assigned a value. Just imho -
Jeremy Iglehart almost 8 years@Oriol I actually like your reasoning the most. Please post an answer to this effect and I will accept it. ( I might even add a few edits if needed )
-
Jeremy Iglehart almost 8 years@Oriol, I think what @choz was trying to say (as a few other also mentioned on this question) that if I want to return
undefined
if something else doesn't return earlier - I don't need to because the function's default behavior if you don't return anything is to return undefined - they are just saying that this is not needed. Further... I like what you had to say about built-in getter functions returning null. Please post your answer to that effect and I will accept it. -
Ryan Laboucane almost 8 yearsYah @Oriol, this is why I actually enjoy debates, even on Q/A sites. It's really good to get counter examples. And you've provided a good one.
-
Jeremy Iglehart almost 8 yearsafter reading this I decided to suggest the
void 0
technique for future viewers of this answer. I also added some code to try and make your point more clear. Thank you for your answer! -
Jeremy Iglehart over 6 yearsI see what you're doing there - and I can't say you're wrong - because in a sense I think you could do this here and it would be fine. I have a different pattern that I use to do this operation that I like better because I do a "validation" step after. I feel like this is getting validation mixed with returning the value. Here is what I do:
let getStringOrJSON = value => { try { value = JSON.parse(value); } catch(e) { return value; } return value; };
. Now, I'm sure the two returns could be handled differently, and might not win the JS golf competition. It works. -
Jake almost 5 yearsThis rings so true to me. IMO pure functions should return
null
, while functions with side-effects should returnundefined
, when thinking like a functional programmer. -
zett42 over 4 yearsI still prefer to explicitly return
undefined
as it documents the intent of the code. Otherwise, when I see a function that doesn't return anything I have to ask myself if the dev who wrote it, just forgot to return something. -
curv about 4 yearsThis should be the accepted answer. This is how it was intended to be used in the spec
-
Sergio Rosas about 4 years
null
refers to the absence of anyobject
value. As much as I like to use it because it's the same word from other languages, a number or a string should be undefined, not null, according to the spec (also that's whytypeof null === 'object'
) -
chiliNUT about 4 years@SergioRosas can you link to the spec that says that undefined should be used for a number or a string?
-
Sergio Rosas about 4 yearsI'm not saying
undefined
should only be used for string number and non objects, or that you can't use it to say absence ofobject
value, but just from those specsnull
seems to be reserved for absence ofobject
value. In the end, how you useundefined
ornull
depends on your code and how you define your interfaces -
chiliNUT about 4 yearsI don't read it that way. I read it as: If you define a variable but don't initialize it, it will instead have an initial value of undefined. Null should be used by the programmer to intentionally indicate that a variable is empty. IMHO undefined should never be assigned to a variable by the programmer, leave it up to the js engine to use it. The term "object" value is misleading, since in JS even the primitives behave like objects for the most part due to autoboxing
-
Sergio Rosas about 4 yearsYeah, that makes sense. To be fair, I don't mind using one over the other (although I'm more used to
null
) as long as you stick with one, but having 2 values to indicate absence of value (whatever the "type") is always confusing -
Ariod over 2 yearsOn the other hand,
array.find()
returnsundefined
if the array doesn't contain searched value. It's not consistent, I agree. -
juliushuck almost 2 yearsAren't the default JS functions conflicting with this? When I use the find function, for example, it returns undefined when no value was found. But it could have returned something when I inputted something else, right?