Skip to content

Commit 5c98251

Browse files
authored
Add a JSON section to discussion of null vs undefined
Understanding how null/undefined work with JSON encoding and remote databases is something I'd wish I known about when I first read through this and opted to go exclusively with undefined.
1 parent 99b2261 commit 5c98251

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

docs/javascript/null-undefined.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,28 @@ function toInt(str: string): { valid: boolean, int?: number } {
102102
}
103103
```
104104

105+
### JSON and serialization
106+
107+
The JSON standard has support for encoding `null` but not `undefined`.
108+
109+
```ts
110+
JSON.stringify(null); // "null" (a string representing null)
111+
typeof( JSON.stringify(null) ); // "string"
112+
JSON.parse( JSON.stringify(null) ); // null
113+
114+
JSON.stringify(undefined); // undefined (JSON.stringify didn't return a string!)
115+
typeof( JSON.stringify(undefined) ); // "undefined"
116+
JSON.parse( JSON.stringify( undefined ) ); // SyntaxError
117+
```
118+
119+
As a result, JSON-based databases may support `null` values but not `undefined` values.
120+
When JSON-encoding an object with an attribute that is null, the attribute will be included with its null value, whereas an attribute with an undefined value will be excluded entirely.
121+
122+
```ts
123+
JSON.stringify({n: null, u: undefined}); // "{"n":null}"
124+
```
125+
126+
Setting attribute values to undefined can save of storage and transmission costs, as the attribute names will not be encoded. However, this can complicate the semantics of clearing values, as you cannot communicate the intent to clear an attribute by settings its value to undefined before encoding it. Since attributes set to `null` are encoded, you can transmit the intent to clear an attribute by settings its value to `null` before encoding and transmitting the object to a remote store (though often at the cost of causing the attribute name to be stored).
105127

106128
### Final thoughts
107129
TypeScript team doesn't use `null` : [TypeScript coding guidelines](https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines#null-and-undefined) and it hasn't caused any problems. Douglas Crockford thinks [`null` is a bad idea](https://www.youtube.com/watch?v=PSGEjv3Tqo0&feature=youtu.be&t=9m21s) and we should all just use `undefined`.

0 commit comments

Comments
 (0)