To check what is the data type of variable in JavaScript, use the typeof operator. The typeof is a unary operator returns a string indicating the type of the unevaluated operand. The null value describes the intended absence of object value. To check the typeof null, use the following code.

// app.js

data = null

console.log(typeof(data))

Output

object

You can see that nullis an object in JavaScript. But null is primitive value in JavaScript like StringNumber, Boolean, undefined, and Symbol. Regrettably, if you call typeof operator on null values, it returns “object“.

JavaScript null is a primitive value, but its data type is an object. Now, this is a historical bug in JavaScript from the beginning that has never been fixed by developers.

The null is a falsy value. What I mean by that it takes as false if constrained to a boolean.

data = null

if (data) {
  console.log('The null value is not falsy')
}
else {
  console.log('The null value is falsy')
}

Output

The null value is falsy

That means if you want to check for a null value, then if-else statement might not be helpful for you because it returns falsy results that can lead you to miscalculation.

So, using the typeof operator to check for a “null” value does no good and will lead to the wrong path.

#javascript #null #programming

JavaScript Null Check: How to Check Null using Object.is()
1.65 GEEK