Search code examples
javascriptprototypeprototype-chain

JavaScript, the top of the prototype chain is null, how to prove it by code?


Javascript checks for the property on object.prototype, object.prototype.prototype, and so on until it hits null. At that point, Javascript returns undefined.
But how to prove the top of prototype chain is null rather than undefined?


Solution

  • Iterate with a while loop, and use Object#getPrototypeOf to get the prototype of the current object:

    let object = {};
    
    while(object = Object.getPrototypeOf(object)) {}
    
    console.log(object);