Search code examples
javascriptobjectprototype

In Javascript all objects have prototypes, except for the base object


for clarifying, there is an interview question's answer on github that says :

All objects have prototypes, except for the base object. The base object is the object created by the user, or an object that is created using the new keyword. The base object has access to some methods and properties, such as .toString. This is the reason why you can use built-in JavaScript methods! All of such methods are available on the prototype. Although JavaScript can't find it directly on your object, it goes down the prototype chain and finds it there, which makes it accessible for you.

I've read this answer several times, but unfortunately it did not help me, could anyone explain it in a more understandable way?.

Also the link to answer is here.


Solution

  • The vast majority of objects you'll encounter ultimately inherit from Object.prototype. This includes built-in objects and objects created with object literal syntax, among many others.

    const obj = {};
    console.log(Object.getPrototypeOf(obj) === Object.prototype);

    A very few objects, including Object.prototype itself, do not inherit from anything. This will only occur if the object is explicitly created with Object.create(null).

    console.log(
      Object.getPrototypeOf(Object.prototype) === null,
      Object.getPrototypeOf(Object.create(null)) === null
    );