Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Object.keys(anObject) return anObject's prototype? [duplicate]

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 the in operator, you can use the hasOwnProperty 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?

like image 200
Richard Avatar asked Aug 20 '18 11:08

Richard


People also ask

What does object keys return JavaScript?

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.

Does object keys guarantee order?

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.

Why does object keys return string?

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.

Do objects have prototype property?

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.


1 Answers

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
like image 138
Luca Kiebel Avatar answered Sep 18 '22 06:09

Luca Kiebel