Search code examples
javascripthtmljavascript-objects

If a property of an Object is not found (Obj Constructor) return value is Not undefined. Why?


Consider a basic example where I am trying to ask for a property which doesn't exist in an object

CASE-I: (General Object)

var obj1 = {
  name: "Jack",
  age: 29
} 

console.log(obj1.city); 

Answer: undefined

This means that if there is a property which is not present, it is rightly referred to as undefined.

CASE-II: (Object Constructor)

Now, I am going to do the same - first making a string which inherits from String Constructor which inherits from Object Constructor. The __proto__ of Object-Constructor doesn't have a property named __proto__ so the answer should be undefined. But rather (strangely) it returns null. Which is beyond understanding.

As far as I know, if the property of an Object is not found - its value should be `**undefined**` and not `**null**`. 

enter image description here

Now, someone please help out in understanding - that after going up the prototype chain the concepts and implementations should remain the same. So, if the __proto__ property of Object Constructor is not found, Why the answer should not be undefined but rather null ???


Solution

  • The way Javascript was designed, null is at the top of the prototype chain of every object. As the specification says, for the internal method GetPrototypeOf, its type signature is ( ) → Object | Null, and it:

    Determine the object that provides inherited properties for this object. A null value indicates that there are no inherited properties.

    Accessing the __proto__ property of an object, or using Object.getPrototypeOf will invoke that internal method. The __proto__ property does exist on most objects (so it doesn't return undefined), but the object it's called on is not guaranteed to have an internal prototype (and if it doesn't, that operation returns null).

    See how __proto__ is a getter/setter on Object.prototype:

    console.log(Object.getOwnPropertyDescriptor(Object.prototype, '__proto__'));

    That property will exist for any object that goes through Object.prototype, which most do. The getter may return null.

    Note that if you create an object which does not inherit from Object.prototype, the __proto__ property will not be in the prototype chain, and you'll get undefined:

    const obj = Object.create(null);
    console.log(obj.__proto__);