Search code examples
javascriptobjectprototype

A map created with Object.create(null) has toString property


I am reading Eloquent JavaScript (https://eloquentjavascript.net/), and in Chapter 6, Marjin Haverbeke suggests one way of creating our own version of a map is to use Object.create(null). The example given in the book is

console.log("toString" in Object.create(null)); //null

I tried creating a map using this method. Here is what I did :

let ages = Object.create(null); 
ages = {Boris : 29, Liang : 22, > Julia : 62};
console.log("Do we know toString's age?", 'toString' in ages);
//returns true

I expect the last console.log to return false, but it gives true. Why is this? How do I use this idea to create a map that does not inherit the toString property? Note : I am vaguely aware of the map datatype, but I am trying to figure this out for conceptual understanding.


Solution

  • You reassigned ages to an object literal, which does inherit toString properly. The object created via Object.create(null) no longer has any reference after the ages variable is reassigned. If you did not reassign ages and simply assigned it properties, it would not have the toString property, as you would expect:

    const ages = Object.create(null); 
    Object.assign(ages, {Boris : 29, Liang : 22, Julia : 62});
    console.log("Do we know toString's age?", 'toString' in ages);
    
    // similarly:
    
    const ages2 = Object.create(null);
    ages2.Boris = 29;
    ages2.Liang = 22;
    ages2.Julia = 62;
    console.log("Do we know toString's age?", 'toString' in ages);