It's Null and Undefined

Null and undefined sneak into our code all the time. Either we forgot to assign a variable to an object in memory, a response from the database, or API came back with an empty object, the list is endless.

Both null and undefined are similar and may sometimes be used interchangeably. The difference is subtle.

A variable with a value of undefined means that it is not initialized.

Null describes the intentional absence of the value.

In statically typed languages, such as Java, variables with object type are initialized with null. Primitive values are initialized by their own values. Such languages do not have undefined as a type.

Since Javascript variables can either be primitives or objects, Javascript undefined means that the variable is neither an object nor a primitive value.

Checking for undefined or null values

The following statements might be used to check for the presence of undefined or null: if(x===undefined ) ..... if(x===null) ....

However, one should avoid using typeof operator to check for nulls: typeof null === object ( a known javascript bug) if(!x) { // falsy statement x might be: undefined, null, false, 0, or Nan }

Handling null and undefined values in data

There are two essential operators that make it easier to work with such values; the nullish coalescing operator (??) and the optional chaining operator (?.).

Nullish Coalescing operator (??)

If you receive null or undefined as a value, sometimes, it might not make sense to use such a value. You can provide a default value, to act as a fallback. It can be implemented as:

x !==undefined && x!==null ? x: y However, the bullish coalescing operator makes our work easier. The above expression can be rewritten as: x??y

Optional Chaining (?.)

This operator enables a developer to access the properties of an object. It can come in handy while dealing with nested properties. Before optional chaining was available, we would have to write our code like this:

// if UserData.city is truthy (not nullish), evaluate and return userData.city.address const userAddress= userData.city && userData.city.address

With optional chaining, the above code can be rewritten as: const userAddress=User?.Data?.city?.address

The downside with optional chaining is that deeply nested object properties are hard to manage, debug or refactor.