by recursive · 5y ago · 0 comments
null: the value exists but is not set.
undefined: the value does not exist.
JSON.stringify on an undefined property removes that property.
JSON.stringify on null keeps that property as null.
A codebase that does not distinguish between null and undefined is a less flexible codebase.
At the end of the day it would have been much nicer for there to only have been one nothing type but what’s done is done.
Element.{firstChild, nextSibling} being null means “I know what firstChild (or nextSibling) is, but this element doesn’t have one.”
It would be categorically wrong for things like Element.{firstChild, nextSibling} to be undefined.
I’ve seen null/undefined semantics play out; they more or less collapse under the slightest of deadline pressures or scaling of team sizes. There are infinite ways to splice the idea of “emptiness” or “lack of data” and any definition you provide (the definitions both you and OP provide give a lot of wiggle room) would be interpreted fifteen ways by fifteen developers, so much so that even changing hands just once will cause any null/undefined distinctions to sublimate in any codebase.
There are so many languages which do just fine with one null type; I don’t understand why JavaScript developers have to do these sorts of mental kinesthetics to justify the existence of two in JavaScript, especially given the more or less insane fact that `typeof null === "object"`. If you consistently use undefined or null exclusively internally, and accept both via the == null trick externally, you can pretty much avoid having to deal with null/undefined semantics entirely.
var x = {}.foo;
var y = (function() {})();
These are contrived examples, but they represent things done by very reasonable code. There are all kinds of ways that `undefined` can get assigned into a variable. It's inevitable that those cases would have to be handled.Except, you can still differentiate between them:
> ({ foo: undefined }).hasOwnProperty('foo')
true
> ({ }).hasOwnProperty('foo')
false
So now you have two ways of specifying a missing property, instead of one. null vs. undefined is a really annoying language misfeature to me, especially with some of the other weird behaviors that it has: > [].length
0
> [].map(v => 123)
[]
> [].map(v => 123).length
[]
> [undefined].length
1
> [undefined].map(v => 123)
[123]
> Array(1).length
1
> Array(1).map(v => 123)
[]
> Array(1).map(v => 123).length
1
If you need to remove a property from an object, just use delete obj.foo; instead of setting it to undefined. JSON.parse(JSON.stringify(obj)).hasOwnProperty('foo')
false
Thing is, other parts of the code might actually serialize and unserialize objects. If you rely on a prop being 'undefined' meaning "prop is unknown like the firstName", as OP suggested, you might be in for a surprise."Less flexible" != "Less correct" or even "less good".
It's true that these are subtly different concepts. It's arguable whether they are helpful distinctions for the long-term health of a codebase.
Sorry if I am misunderstanding your statement.
T | null signifies that it can be cleared by using setState({prop: null}).
T | undefined means that it may start out undefined, but if it becomes defined it'll probably stay that way. If you try doing setState({prop: undefined}), it won't work.
const x = {};
x.foo // returns undefined
const y = { foo: undefined };
y.foo // also undefined
Basically a member not being provided will return undefined, whereas `null` had to actually be set. Hence I think the tendency for checking for the absence of something via `undefined`, while expressing the deletion of something with `null`. Sure, you can assert more specific types in TypeScript to step around that, or you can do something less intuitive like checking for `keyof` to detect absence; but this is both straightforward and presents less issues when interfacing with inputs from non-typescript-using users.
Some of the rebuttals below seem to be saying "But I use them differently!" Bully for them, but 99% of the time when it's not set, you don't really care why it's not set because it's not defined yet or because it's been set to `null`.
And any time they assume it can only be null OR undefined but not either, there's a chance for a bug. Even if I "know" it can only ever be null and not undefined, it's safer to just say != null rather than !== null.
Treating them differently in a code base is a legit semantic, but testing with != null works no matter the intended semantics.
The semantic differences seem to be local at best. In any case, there's plenty of code that legitimately doesn't concern itself with any of that.
I've never ever run into this because I never use undefined for anything other than stuff that's explicitly not set, and I have no fucking idea why other people are. But I can definitely see it causing bugs if you do stuff like use '!=' everywhere and treat null and undefined as the same thing.
This is why the original comment is wrong. You should be narrowing your types where possible. It costs nothing to just always use null if you're explicitly setting something, then you can use '!==' wherever you want, which means that if someone else sets something to undefined you'll catch the bug straight away when it's easiest to catch.
If you treat them the same you're just asking for some 3rd party lib to do a '!== null' or accidentally overwrite a "null" with a default parameter you're not expecting, and that's way, way harder to troubleshoot.
You could just as easily run into a bug with 3rd party lib code by distinguishing between the two when that library doesn't.
The only reason I've ever intentionally used `null` in my own code is that it precedes `undefined` in the default array sort. But if I ever found myself using library code that required `null` for something, I'd say "Huh. That's weird." And then I'd pass it a `null`.
Of course, TypeScript will say that 'null' can't be passed to createNewMessagesResponse directly. However, data gets pushed around a code base a lot and might go through third party packages or come in from an API response and could very well be 'null'. I proactively don't check for 'undefined', because I can't really trust this to be 'undefined'. Furthermore, in the example OP provided, 'null' and 'undefined' should have the same result (no message is shown, because no number was passed to the function).
I see more room for error with being explicit as a default than generalizing as a default.