Is it better to return `undefined` or `null` from a javascript function?

JavascriptFunctionNullReturnUndefined

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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:

https://stackoverflow.com/questions/6429225/javascript-null-or-undefined

Solution 2 - 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.

Solution 3 - Javascript

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 4 - Javascript

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 - Javascript

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.

Solution 6 - Javascript

Here's an example where undefined makes more sense than null:

I use a wrapper function for JSON.parse that converts its exception to undefined:

// parses s as JSON if possible and returns undefined otherwise
// return undefined iff s is not a string or not parseable as JSON; undefined is not a valid JSON value https://stackoverflow.com/a/14946821/524504
function JSON_parse_or_undefined(s) {
	if ("string" !== typeof s) return undefined

	try {
		const p = JSON.parse(s)
		return p
	} catch (x){}

	return undefined
}

Note that null is valid in JSON while undefined is not.

Solution 7 - Javascript

I would argue that in this case, null should be returned.

If you consider the question from a theoretical computer science point of view then undefined is used to indicate non-termination/ non-computability (i.e. the placeholder for an undefined point x of a partial function f which is often written f(x) = ⊥).

getNextCard however seems to be able to compute the next card (if it exists) and also be able to compute if there is no next card. In other words, the function is total since it terminates for every input.

That being said, a special value signalling termination without meaningful result (i.e. "there's no card I can return for this input") is required and this for me is null not undefined.


NOTES:

You can see some support for this argument in some other typed languages as well where termination without meaningful result are expressed using an option type (sometimes also referred to as nullable type). An example for this is is Maybe in Haskell.

On the other hand, we of course do not know what undefined in JavaScript is really supposed to mean. So, the analogy to undefined is a bit tenous. Moreover, since we always want to work with total functions, this amounts to saying "never return undefined from a function". Which seems to be a bit strict, since it would limit the use of undefined to properties/ variables which have not been set.

In the end, my personal preference is never to return undefined where I can return null and I would also argue that this is the better coding convention (because among other things x !== null is shorter than typeof x !== 'undefined').

Solution 8 - Javascript

First answer is right. They have theoretically different meaning. However it's not always clear which to pick up.

I tend to use null in my development although I think that's completely subjective thing.

I use that mostly because:

  1. undefined variable might be overwritten in old browsers so returning it is a little bit more complicated. This same issue forces you to use typeof var === 'undefined' when getting function results. link

  2. Other languages tend to use null widely, a lot of them don't even have undefined (php for example). That gives me kind of consistency when quickly swapping between languages.

Solution 9 - Javascript

I think it is very debatable what to use. I prefer code that is semantically as accurate as possible, so I think undefined is appropriate in this case.

I think of null assignments as meaning "a variable set to nothing". This is as opposed to undefined meaning "this thing isn't there at all"

As a previous answer pointed out, returning undefined has issues, and it's completely up to you whether that bothers you. It wouldn't bother me.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJeremy IglehartView Question on Stackoverflow
Solution 1 - JavascriptchiliNUTView Answer on Stackoverflow
Solution 2 - JavascriptngrymanView Answer on Stackoverflow
Solution 3 - JavascriptOriolView Answer on Stackoverflow
Solution 4 - JavascriptDanView Answer on Stackoverflow
Solution 5 - JavascriptchozView Answer on Stackoverflow
Solution 6 - JavascriptmasterxiloView Answer on Stackoverflow
Solution 7 - JavascriptFK82View Answer on Stackoverflow
Solution 8 - JavascriptMaciej PaprockiView Answer on Stackoverflow
Solution 9 - JavascriptRyan LaboucaneView Answer on Stackoverflow