Skip to the solution
MediumDSAAsked in 20247 min read

Custom Object.create polyfill

2.3k views

The problem

Problem, as an interviewer would state it: "Implement Object.create from scratch — creating a new object with a specified prototype, correctly handling the special Object.create(null) case (an object with NO prototype at all), matching real native behavior exactly."

Examples:

Code
const parent = { greet() { return "hi"; } };
const child = myObjectCreate(parent);
child.greet(); // "hi" -- inherited via the prototype chain

Clarifying questions expected:

  • Does Object.create(null) need to genuinely produce an object with NO prototype at all, not just an object linked to Object.prototype?
  • Does the optional second propertiesObject argument (matching real Object.defineProperties's own format) need to be supported?
  • What should happen if proto is neither a real object nor null?

Code / implementation expected: Yes — real, direct proof of correct prototype linking, AND real, direct proof that myObjectCreate(null) produces a genuinely null-prototype object, not one silently linked to Object.prototype.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

7 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: the corrected Object.create polyfill matches real native behavior, including the genuinely null-prototype case that a naive new F() approach silently got wrong

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 66 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Implement a JSONPath-Lite Query Evaluator (Supports Wildcards Like $.users[*].name)

Continue