6 Secrets about “null” and “undefined” that You Should Know

Maybe we don’t know “null” and “undefined” at all

fatfish
3 min readApr 19

--

Photo by Steve Tsang on Unsplash

I feel ashamed that I didn’t know everything about null and undefined, although I have been working for many years.

If you are similarly confused as I was, this article will tell you everything.

The basics that everyone knows about

This is a very interesting picture, and perhaps it has expressed the essential difference between null and undefined.

Both null and undefined stand for "null", so what is the main difference between them?

  1. undefined means that the variable has not been defined yet.
  2. null means that the variable is defined but it does not point to any object in memory.

This is the most basic difference between null and undefined, which you must know very well.

1. Why does “typeof null” return ‘object’?

null is not the same as {}, it is not an object type of data, but why does typeof null return object?

In fact, it is a bug that existed in JavaScript since the beginning of its design, but could not be fixed until now.

In the initial version of JavaScript, all values were stored in 32 bits. The first 3 bits represent the token of the data type, and the rest of the bits are the value.

For all objects, the first 3 bits of the object are marked with 000 as the type tag bit. In earlier versions of JavaScript, null was considered a special value to correspond to a null pointer in C. However, JavaScript does not have pointers as in C, so null means nothing or void and is represented by all 0’s (32).

--

--

fatfish

Hi friends, I am a front-end engineer from Alibaba, let’s code happily together.