Clean • Professional
In JavaScript, displaying objects is essential for debugging, logging, and data transfer.. JavaScript provides several ways to display objects for inspection and serialization:
console.log – Outputs objects to the console.console.dir – Displays a detailed, interactive view of an object’s properties.JSON.stringify – Converts objects to JSON strings for serialization or structured logging.console.table, console.group) enhance readability for arrays or complex objects.console.logThe most common method to display an object’s contents in the console, typically used for debugging.
Syntax:
console.log(object);
Example:
const person = {
name: "John",
age: 30,
address: { city: "Mumbai", country: "India" }
};
console.log(person);
// Output:
// { name: "John", age: 30, address: { city: "Mumbai", country: "India" } }
console.dirDisplays an interactive, detailed view of an object’s properties, often more structured than console.log.
Syntax:
console.dir(object);
Example:
const person = { name: "John", age: 30 };
console.dir(person);
JSON.stringifyConverts an object to a JSON string, useful for serialization, logging, or transmitting data.
undefined, and symbols.TypeError.Syntax:
JSON.stringify(value[, replacer[, space]]);
value – Object to convert.replacer (optional) – Function or array to filter/transform properties.space (optional) – Number of spaces for indentation.Example:
const person = {
name: "John",
age: 30,
job: undefined,
greet: function() { console.log("Hi"); },
[Symbol("id")]: 123
};
console.log(JSON.stringify(person));
// Output: {"name":"John","age":30}
// Pretty-print with indentation
console.log(JSON.stringify(person, null, 2));
/* Output:
{
"name": "John",
"age": 30
}
*/
Replacer Example:
const replacer = (key, value) => (typeof value === "number" ? value * 2 : value);
console.log(JSON.stringify(person, replacer)); // {"name":"John","age":60}
a) console.table
Displays object properties in a tabular format, ideal for arrays of objects or simple key-value pairs.
const people = [
{ name: "John", age: 30 },
{ name: "Alice", age: 25 }
];
console.table(people);
b) console.group
Groups related logs for nested objects, improving readability.
console.group("Person");
console.log("Name:", person.name);
console.log("Address:", person.address);
console.groupEnd();
Circular References:
console.log and JSON.stringify fail with circular references.
const obj = {};
obj.self = obj;
console.log(obj); // [Circular] or incomplete
// JSON.stringify(obj); // TypeError
Non-Enumerable Properties:
Object.defineProperty(person, "id", { value: 123, enumerable: false });
console.log(person); // id not shown
console.dir(person); // May show id in some environments
Custom Display: Define a toString method to customize object display.
const person = {
name: "John",
age: 30,
toString() {
return `${this.name}, ${this.age} years old`;
}
};
console.log(person.toString()); // "John, 30 years old"Â