What is the Object.getPrototypeOf method in JavaScript?

We can use the getPrototypeOf method to get the prototype property of the object (i.e, the [[Prototype]] property value of an object).

Syntax

Object.getPrototypeOf(obj)

The above method will return the prototype of the passed object. If the passed object has no prototypenon-inherited object, then null is returned.

Example

let user = {name: "hi"};
let proto = Object.getPrototypeOf(user);
console.log("user object is ", user);
console.log("prototype of user object is", proto);
console.log("\n checking if the prototype of the user object is Object.prototype");
console.log( Object.getPrototypeOf(user) === Object.prototype );

In the code above, we have created a user object – upon getting the prototype of the user object, it will return Object.prototype.


Let’s look at another example with inherited objects:

let human = {type: "human"};
let male = Object.create(human);
male.gender = "male";
let user = Object.create(male);
user.name = "Ram";
console.log("Human - ", human);
console.log("Male - ", male);
console.log("User - ", user);
console.log("\n\nGetting Prototype\n")
console.log("Prototype of user: ", Object.getPrototypeOf(user));
console.log("Prototype of male: ", Object.getPrototypeOf(male));
console.log("Prototype of human: ", Object.getPrototypeOf(human));

In the code above, we have a human object from which a male is created, from the male, the user is created. So, prototype of:

  • user - male
  • male - human
  • human - Object

The getPrototypeOf method returns null for Objects with no prototype.

let obj = Object.create(null);
console.log("Prototype of obj is", Object.getPrototypeOf(obj) );

The above code will return null because the obj has no prototype.


Free Resources