24

While I execute Object.prototype in browser console, i am getting all the properties and methods available inside Object.prototype. This is as expected but when i am executing exactly the same thing in NodeJS terminal I am getting an empty object {}. Could anyone please explain me why its like this? I have attached screenshots of both.

Browser

Terminal

3
  • 10
    This is purely the way the two different systems choose to display an object. Jul 8, 2018 at 16:10
  • 1
    @lonesomeday Well {"key": "value"} will display as {"key": "value"}, not as {}. Are you sure?
    – Ivan
    Jul 8, 2018 at 16:12
  • 2
    @Ivan Yes. The difference is that Node doesn't display non-enumerable properties, whereas the Chrome console displays them faded out. Jul 8, 2018 at 16:15

2 Answers 2

21

It is because the console.log() in node use util.inspect(), which uses Object.keys() on objects, and it returns enumerable properties only. And Object.prototype contains non-enumerable properties, that is why it returns empty node.

Similar behavior can be observed in the below snippet, when we console.log(Object.prototype) it logs an empty {};

console.log(Object.prototype);

But when we explicitly define an enumerable property in Object.prototype it logs an object containing that property :

Object.defineProperty(Object.prototype, 'property1', {
  value: 42,
  enumerable : true
});
console.log(Object.prototype)

For Reference

2
  • 5
    I would add that there is no agreed-upon standard for how an inspector (debugger, console, etc...) should display things, thus different environments choose slightly different implementations.
    – jfriend00
    Jul 8, 2018 at 17:09
  • 1
    Why are props of Object.prototype not enumerable by default?
    – Bruce Sun
    Oct 4, 2021 at 3:35
13

By the way, you can use Object.getOwnPropertyNames if you want to know or access these properties.

> Object.getOwnPropertyNames(Object.prototype)
[ 'hasOwnProperty',
  'constructor',
  'toString',
  'toLocaleString',
  'valueOf',
  'isPrototypeOf',
  'propertyIsEnumerable',
  '__defineGetter__',
  '__lookupGetter__',
  '__defineSetter__',
  '__lookupSetter__',
  '__proto__' ]

It won't list other properties you might find in chrome dev console like scope or the value of promises. But it's good enough!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.