maroodb
maroodb

Reputation: 1108

How console.log(object) works in background?


I have this code:

const obj = {name: 'maro', age: 77}

console.log(obj); // it logs { name: 'maro', age: 77 }

It seems like evident! but I want to know how console.log internally works ? which methods of "obj" it calls to get the "{ name: 'maro', age: 77 }"

obj contains those properties:

obj.__defineGetter__      obj.__defineSetter__      obj.__lookupGetter__      obj.__lookupSetter__      obj.__proto__             obj.constructor           obj.hasOwnProperty
obj.isPrototypeOf         obj.propertyIsEnumerable  obj.toLocaleString        obj.toString              obj.valueOf    obj.age        obj.name

But none of them returns "{ name: 'maro', age: 77 }"!

even obj.toString() returns '[object Object]'

Upvotes: 3

Views: 203

Answers (4)

Alberto Trindade Tavares
Alberto Trindade Tavares

Reputation: 10356

As you can see in Node.js console.log documentation, it uses, behind the scenes, util.format to format its output.

According to util.format documentation, it returns a string representation of an object with generic JavaScript object formatting, similar to util.inspect.

You can see its actual implementation, at least for Node.js, here: https://github.com/nodejs/node/blob/75dc8938a40100a53323ed87159a1ab2f149ceca/lib/internal/util/inspect.js#L1567. Have fun reading this code :)

Upvotes: 1

Ankit Kumar Rajpoot
Ankit Kumar Rajpoot

Reputation: 5600

You can use valueOf().

const object1 = {name:"ankit",age:27}
console.log(object1.valueOf());

Note: Objects in string contexts convert via the toString() method, which is different from String objects converting to string primitives using valueOf. All objects have a string conversion, if only "[object type]". But many objects do not convert to number, boolean, or function.

Upvotes: 0

marek63
marek63

Reputation: 21

It is obj.valueOf() if I'm not mistaken. Here is the documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf

Upvotes: 2

JosePena
JosePena

Reputation: 1

If you need the name 'maro' and the age 77, you need use obj.name and obj.age...

Upvotes: -1

Related Questions