Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object.prototype returns empty object in Node

Tags:

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

like image 412
Shirshendu Bhowmick Avatar asked Jul 08 '18 16:07

Shirshendu Bhowmick


People also ask

What does an empty object return in JavaScript?

Use the Object. entries() function. It returns an array containing the object's enumerable properties. If it returns an empty array, it means the object does not have any enumerable property, which in turn means it is empty.

Which of the following will create an empty object?

New Keyword. The Object constructor creates an object wrapper for a given value. If the value is null or undefined , it will create and return an empty object.

How do I check if an object is empty in node JS?

keys method to check for an empty object. const empty = {}; Object. keys(empty). length === 0 && empty.

Why empty object is true in JavaScript?

There are only seven values that are falsy in JavaScript, and empty objects are not one of them. An empty object is an object that has no properties of its own. You can use the Object.


1 Answers

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

like image 105
amrender singh Avatar answered Oct 03 '22 23:10

amrender singh