loading...

re: Unhealthy Code: Null Checks Everywhere! VIEW POST

FULL DISCUSSION
 

What about using undefined instead of null?
Better or worse?

 

Undefined in javascript is what null is in other languages. I think its better to use it. Best is to avoid both.

But a lot of js developers expect a null. A lot of libs return null (some even return either, with no reason for one or the other). And js itself also returns null, for example getElementById.

 

The reason I use it is that if you see a null you known that it was explicitly set, where as undefined means it hasn't been touched.

Would you recommend just sticking to undefined rather than mixing null and undefined?

Do your code ever do things differently based on if a variable contains a null or if it contains a undefined?

Let me try a bad analogy: If couldYouBuyMeSomeFlowers() returns null, it would be reasonable to assume that the florist is out of flowers (why else would he give us an explicit null instead of nothing).. But if it returns undefined.. Did the method forget to go to the florist? Should i call couldYouBuyMeSomeFlowers() again until it returns flowers or null? Or is the florist gone? No matter the reason, I still don't have flowers and I will have to throw a PartyCanceledError("Sorry, we can't have a party without flowers").

If i needed a reason why the method failed, it would be better if the method just threw an error instead. StoreNotFoundError or NotEnoughMoneyError. Or a Promise<Flower[]> for a later delivery. I could deal with that.

Code of Conduct Report abuse