Dev.to WebDev 🛠 Dev 👁 0 📖 1 min read

The quirk of null...Null

In English, null means nothing, but in JavaScript, that nothing can become a headache. Let's overthink it and try to understand why and how. As per MDN, In JavaScript, a primitive (primitive value, primitive data typ

In English, null means nothing, but in JavaScript, that nothing can become a headache. Let's overthink it and try to understand why and how.

As per MDN,

In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods or properties.

Since null is one of the 7 primitive data types, it is not an object.

What about typeof null? It returns the string "object".

Well, though null is a primitive data type, typeof null is not. typeof null is just a string, the result of using typeof, which is a way to check the type of any value. And typeof null === "object" is nothing but a bug that was left unsolved intentionally, so old websites wouldn't break.

So what about typeof Number, typeof String etc. returning "function"?

That's a different thing, and it's called a constructor). By convention, a constructor starts with a capital letter, and it is completely different from the same name with a lowercase letter because JavaScript is case-sensitive. So, "number" is completely different from Number. One is the type label typeof returns for values like 5, and the other is a constructor function.

So why does typeof Null/Undefined return "undefined"?

It's easy to mix things up as a beginner, but there is no such thing in JavaScript as Null or Undefined with a capital N/U. They are undeclared names, and typeof doesn't throw an error on undeclared names.

typeof Null;        // "undefined"  (undeclared name; typeof doesn't throw)
Null;               // ReferenceError: Null is not defined

Separately, null & undefined have no constructor function or wrapper object. That's also why property access on them fails instead of autoboxing:

null.toString();       // TypeError
undefined.toString();  // TypeError

So what did we learn from this article? Literally nothing aka null.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.