Avoid Assigning undefined to an Object Property
A property value should be any JavaScript value except for undefined
. If you do something like this (albeit it is legal):
|
|
will leads to confusing code. Because when accessing the property value:
|
|
It will returns undefined
. But you are not sure if it means the property exists or not or the value of the property is set to undefined
. Therefore, you should do:
|
|
This indicates that the property is expected, and with the value of null
.
You do be able to check the existence of a property by:
|
|
But more importantly, if you serialize the object with JSON.stringify
, properties with undefined
will be omitted:
|
|
According to JSON specification, a value can be a string
in double quotes, or a number
, or true
or false
or null
, or an object
or an array
. undefined
is not a valid JSON value.
null
is fine:
|
|
So, for the best practice, avoid assigning undefined
to a property of an object. Use null
to indicate the expected property without a value. This will increase portability when using JSON to serialize.