DEV Community

Discussion on: The Semantics of Falsy Values

 
blindfish3 profile image
Ben Calder

Agreed: I think I already said that it makes sense for null not to have a fallback ;)

Anyway, I had time to think of some examples to illustrate when it may make more sense to return undefined from a function:

  • a helper function to select an optional property that may be deeply nested on an object. If I try and directly access an object property that doesn't exist I get undefined. It makes more sense to me to also return undefined from my helper function than to explicitly return null
  • a function that processes some form of optional input. If input is not provided it is undefined. In this case I'd be inclined to also return undefined

In both these cases it may be desirable to allow another function that accepts these return values to provide a default fallback.

To be clear: these comments aren't intended as criticism. I found your article interesting; especially since misunderstanding of falsy values and coercion often lead to unintended errors - e.g. the common use of the shortcut if(someValue) to determine that a value is defined falls flat when dealing with numerical input that may be 0...
But I also thought @tom 's question was justified. I think the confusion comes from this line in the article:

It is for this reason why null is more correct and desirable than undefined when returning nothing.

Was that intended to be meant specifically in the context of an object search; or as a general directive for returning nothing from any function? I'd disagree with the latter assertion for the reasons outlined above: I'd argue that context is more important in determining what is a semantically correct falsy value to return than having a rule that is set in stone: "never say never" ;)

Thread Thread
 
somedood profile image
Basti Ortiz • Edited

Oh, no! Don't worry about it. I take no offense because I know that this is an educated discussion. 😉

As for the examples you provided, I definitely agree with them. I think it semantically makes sense to return undefined in your examples since the values of the fields haven't been defined in the first place. In other words, what I'm trying to say that your usage of undefined is truly valid and justifiable in those specific contexts.

In regard to the quote you cited, I see now how my wording can be misinterpreted and may have implied that undefined is "always" wrong. That is my mistake. When I wrote the sentence you quoted, what I meant by it is that null should always be returned if the intent is to literally pass absolutely nothing.