Stuff I Learned


Stuff I Learned


typeof null

Kellen's photo
·Aug 12, 2021·

2 min read

In JavaScript, typeof is a useful operator for parsing data. typeof returns a string that describes the data type of the value passed in.


typeof 1234 // "number"
typeof "abcd" // "string"
typeof false // "boolean"
typeof { foo: "bar" } // "object"

There are a few confusing cases in typeof. These are:

typeof [a, b, c] // "object"
typeof NaN // "number"
typeof null // "object"

Kind of weird, right? The null value being read as "object" is especially unexpected. According to, this is due to the way null is represented in computer memory.

In order to determine a value of null, you will need to also determine that the value is !== null. I had a usecase where I was building a payload and needed to determine if the incoming data was an empty object or was truly null. If the data was an array, I needed to make sure that the value in the payload was an empty array. Likewise, I needed to ensure that null values were not assigned to be an empty array, but remained null.

if (typeof payload[key] === 'object' && payload[key] !== null) {
            payload[key] = []
          } else {
            payload[key] = null

This if statement will check if a value is an object and ensure that the value is not null returning the object type.

Share this