DEV Community

loading...
Cover image for JavaScript Interview Question #47: How Object.setPrototypeOf works in JS

JavaScript Interview Question #47: How Object.setPrototypeOf works in JS

Coderslang: Become a Software Engineer
Teaching you to code at js.coderslang.com - JavaScript, HTML, CSS, Node.js, React.js, React Native
Originally published at learn.coderslang.com ・2 min read

javascript interview question #47

What is Object.setPrototypeOf in JavaScript? How does it work? What’s the output?

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

Theory

The function Object.setPrototypeOf sets the new prototype for any JavaScript object. The object itself doesn’t change, but it "inherits" the behavior of the object used in setPrototype.

You can check it by accessing the __proto__ property before modifying the prototype and after it.

For example, let’s create an object with a single field name and and an array with 3 elements.

const user = { name: 'John' };
const arr = [ 1, 2, 3 ];

console.log('Original state');
console.log(user);            // { name: 'John' }
console.log(user[1]);         // undefined
console.log(user.__proto__);  // {}
console.log(user.length);     // undefined

Object.setPrototypeOf(user, arr); // добавляем прототип arr к user

console.log('Modified state');
console.log(user);            // Array { name: 'John' }
console.log(user[1]);         // 2
console.log(user.__proto__);  // [ 1, 2, 3 ]
console.log(user.length);     // 3
Enter fullscreen mode Exit fullscreen mode

After modifying the prototype of the user, we got access to the "parent" field length and "inherited" the elements of the array arr. Now we can access them by index.

Practice

In our original code snippet happens the same. The user object gets access to the field name from the object of a type Human, but it won’t get any new fields.

The function Object.keys returns an array formed by all the fields that the object has. But not the "inherited" ones. As the user object doesn’t have any "own" properties, the length of this array is 0.


ANSWER: The first console.log prints an empty array to the screen, and the second one prints the string John.

Learn Full-Stack JavaScript

Discussion (0)