Creating a null object is simple, but not in the way you may think.
Consider the below code -
earth
is empty but not null.
See -
1
2
3
4
5
6
7
8
9
10
11
|
console.log(Object.toString(earth));
// function Object() { [native code] }
console.log(earth.__proto__);
// {}
console.log(earth.hasOwnProperty());
// false
console.log(Object.getOwnPropertyDescriptors(earth));
// {}
|
If you want a truly empty object, you would want to do this -
1
|
const nullEarth = Object.create(null);
|
Now the previously tested code yields different results -
1
2
3
4
5
6
7
8
9
10
11
|
console.log(Object.toString(nullEarth));
// function Object() { [native code] }
console.log(nullEarth.__proto__);
// undefined
console.log(nullEarth.hasOwnProperty());
// error: nullEarth.hasOwnProperty is not a function
console.log(Object.getOwnPropertyDescriptors(nullEarth));
// {}
|
The new object is an object all right, but does not have a property and inherits from undefined
rather than an empty object.