Typically if we just use alert(object);
it will show as [object Object]
. How to print all the content parameters of an object in JavaScript?
The JSON.stringify () method is used to print the JavaScript object. JSON.stringify () Method: The JSON.stringify () method is used to allow to take a JavaScript object or Array and create a JSON string out of it.
MDN recommends using console.log(JSON.parse(JSON.stringify(obj)))over console.log(obj)for printing objects. This is done to avoid constant updates to the console whenever the value of the object changes. This method won’t work if you try to concat a string with the object, as shown below:
To make a “real copy” (a clone) we can use Object.assign for the so-called “shallow copy” (nested objects are copied by reference) or a “deep cloning” function, such as _.cloneDeep (obj). Advance your skils with video courses on JavaScript and Frameworks.
When we perform actions with the object, e.g. take a property user.name, the JavaScript engine looks at what’s at that address and performs the operation on the actual object. Now here’s why it’s important. When an object variable is copied, the reference is copied, but the object itself is not duplicated.
This will give you very nice output with an indented JSON object using JSON.stringify
:
alert(JSON.stringify(YOUR_OBJECT_HERE, null, 4));
The second argument (replacer
) alters the contents of the string before returning it.
The third argument (space
) specifies how many spaces to use as white space for readability.
JSON.stringify
documentation here.
If you are using Firefox, alert(object.toSource())
should suffice for simple debugging purposes.
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