4 ms·
Not sure I agree that there is some logical reason why Node.firstChild should be null for an empty element whereas e.g. array[0] should be undefined for an empt
by mantap 6y ago
Not sure I agree that there is some logical reason why Node.firstChild should be null for an empty element whereas e.g. array[0] should be undefined for an empty array. I think the actual reason is just that DOM is an old API. If designed today it would return undefined.
- chrismorgan 6y ago> If designed today it would return undefined. Absolutely not. Null means it knows what you’re asking for, and there’s no value. Undefined means it doesn’t know what you’re asking for. (This includes function calls that don’t return a value, since you’re asking for a value that wasn’t produced—again different from null, which is explicitly producing a value.) Node.firstChild being null for a node with no children is absolutely correct. Undefined would be incorrect. Seeking past the end of an array finds elements that have not been defined, so undefined is correct and null would be incorrect.
- Master_Odin 6y agoExcept in these cases, undefined still can make complete sense if you're willing to rephrase things (like sindresorhus is). For your Node.firstChild example, one could say that if a node has no children, then it's firstChild is not defined as it doesn't exist, and so undefined makes sense. You can construct similar plausible arguments for other usages of null, though you cannot do the inverse.
- ZephyrBlu 6y agoNode.firstChild _is_ defined though, it's just empty. Hence null. An undefined property would be one like Node.helloWorld, which doesn't not exist at all on the object.
- chrismorgan 6y agoNode.firstChild producing null is this conversation: “Hey node, what’s your first child?” “I don’t have a first child.” Node.firstChild producing undefined is this conversation: “Hey node, what’s your first child?” “Huh? What’s a first child? I have no idea what you’re talking about.”