I'm reading Eloquent JavaScript's Map section and I'm having trouble understanding its last paragraph:
If you do have a plain object that you need to treat as a map for some reason, it is useful to know that
Object.keys
returns only an object’s own keys, not those in the prototype. As an alternative to thein
operator, you can use thehasOwnProperty
method, which ignores the object’s prototype.
I then assume that Object.keys
does not return the properties and methods an object gets from the inheritance of its prototype. So I tried the following:
var anObject = {};
console.log(Object.keys(anObject)); //Array []
console.log("toString" in Object.keys(anObject)); //true
console.log(anObject.hasOwnProperty("toString")); //false
Apparently, toString
is in the array returned by Object.keys(anObject)
, but an empty array is returned when I logged its keys? Did I understand the passage wrongly?
Object.keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object . The ordering of the properties is the same as that given by looping over the properties of the object manually.
keys() method, which lets you use a for...of loop, but the order of the resulting object keys is not guaranteed. The behavior is the same for Object. values() or Object. entries() — the order of the object properties can vary from insertion order.
keys() returning string is because types aren't exact. Exact types are a prerequisite for making Object. keys() return keyof T in a sound way.
Every object in JavaScript has a built-in property, which is called its prototype. The prototype is itself an object, so the prototype will have its own prototype, making what's called a prototype chain. The chain ends when we reach a prototype that has null for its own prototype.
You understood the passage correctly, the usage of in
here is wrong though.
It returns true, since the Array that Object.keys(anObject)
returns has a property called toString
in it's prototype. in
also checks the prototype, while hasOwnProperty
only checks the properties an Object actually has (meaning the properties that were "manually added" to the empty Object).
But it doesn't have an "own property" with the name toString
let anObject = {};
let keys = Object.keys(anObject);
console.log("toString" in keys); //true, since there is a property "toString" in the keys.prototype object
console.log(keys.hasOwnProperty("toString")); //false, since there aren't any properties in the object itself
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With