This page looks best with JavaScript enabled

Create Null Object in Javascript

 ·   ·  ☕ 1 min read

Creating a null object is simple, but not in the way you may think.

Consider the below code -

1
const earth = {};

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.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things