[Vuejs]-Should I use Undefined or Null as default for a property that is about to receive its value from a GET response?

3👍

There is no answer to the "should be" part of the question since it is a matter of opinion, but it may be of benefit to contrast the differences between and the commonality of the two.

undefined

Undefined is a data type in JavaScript with a single value, undefined and is

  • Returned from a function by default if no other return value is specified,
  • When reading a variable that has never been initialized,
  • When reading a property of an object that has never been set (including array entries whose subscript is a property of the Array object), and
  • When a accessing a variable, property or function return value that has been explicitly set to undefined – possible because it is a data type after all.

Undefined values are treated as false in a comparison statement or ternary ? expression, excluding strict equality comparisons of the null === false kind.

The undefined data type is not supported in JSON: undefined is converted to null when serializing a data object into JSON text.

null

Null is also a JavaScript data type with a single value null. In many ways it is similar to undefined with important differences:

  • null values never arise by default and must always be explicitly assigned to a variable, property or returned from a function.
  • null is a supported value when serializing data objects into JSON.
  • null has a historic meaning of "no object" or an empty object class similar to the empty set phi in mathematics.

Regarding you choice of usage, initializing product to undefined highlights that the value has not been obtained as yet, but also risks being interpreted as a bug in a function that returns undefined when asked to return product. Returning null resolves any "this is not a mistake" questions and is well established practice.

Leave a comment