Question
Inspecting Object Properties and Values in JavaScript
Question
Is there a built-in JavaScript function similar to PHP's print_r that prints an object's current properties and values? I want to inspect the state of an object while debugging a script.
Short Answer
You will learn how to inspect JavaScript objects during debugging, including the differences between console.log(), console.dir(), Object.keys(), and JSON.stringify(). You will also learn which approach is appropriate for browser and Node.js code.
Concept
JavaScript does not have one universal print_r() equivalent, but it provides several built-in ways to examine an object.
The most common debugging tool is console.log(). It sends a value to the developer console, where browsers and Node.js can display an object's properties in an expandable form.
console.log(user);
For an object-focused view in browser developer tools, use console.dir():
console.dir(user);
When you need the property names yourself, use Object.keys(). When you need a text representation that can be copied or logged, JSON.stringify() can be useful.
Object inspection matters because applications constantly store state in objects: a logged-in user, an API response, configuration settings, form values, and error details. Inspecting that state helps you verify what your code actually received or changed, rather than guessing.
Mental Model
Think of an object as a labelled storage cabinet.
- Each property name is a drawer label, such as
nameoremail. - Each property value is what is inside that drawer.
console.log()lets you place the whole cabinet under a magnifying glass in the console.Object.keys()gives you only the drawer labels.JSON.stringify()writes a simplified text snapshot of the cabinet.
Different tools reveal different views of the same object.
Syntax and Examples
Use console.log() for general debugging:
const product = {
id: 42,
name: "Keyboard",
inStock: true,
price: 79.99
};
console.log(product);
In a browser console, the object is usually expandable so you can inspect its properties.
Use console.dir() when you specifically want an object-style display:
console.dir(product);
List the object's own enumerable property names with Object.keys():
console.log(Object.keys(product));
// ["id", "name", "inStock", "price"]
List both names and values with Object.entries():
for (const [key, value] .(product)) {
.();
}
Step by Step Execution
Consider this code:
const session = {
user: "Ada",
authenticated: true,
attempts: 1
};
session.attempts += 1;
console.log(session);
console.log(Object.entries(session));
sessionis created with three properties.session.attempts += 1reads the current value (1), adds1, and stores2back into the object.console.log(session)displays the object in its current state. Itsattemptsproperty is now2.Object.entries(session)creates an array of[propertyName, value]pairs:
[
["user", ],
[, ],
[, ]
]
Real World Use Cases
-
Inspecting API responses: Log a parsed response to check whether an endpoint returned the fields your UI expects.
const response = await fetch("/api/profile"); const profile = await response.json(); console.log(profile); -
Debugging form submissions: Inspect values before sending them to a server.
console.log({ email, password, rememberMe }); -
Checking application state: Inspect a shopping cart, game state, or current filter settings after a user action.
-
Investigating errors: Log an error object and relevant context when an operation fails.
console.error("Could not save order", { error, order }); -
Writing diagnostic scripts: Use
Object.entries()to print configuration values or environment-derived settings in a readable format.
Real Codebase Usage
In production codebases, developers usually use object inspection intentionally and avoid logging sensitive data.
Log useful context
Instead of unrelated messages, use a descriptive label and the object:
console.log("Checkout payload before request:", payload);
Use console.table() for records
For an array of similar objects, a table is often easier to scan:
const users = [
{ id: 1, name: "Ada", active: true },
{ id: 2, name: "Lin", active: false }
];
console.table(users);
Validate before continuing
Object inspection often helps identify invalid inputs, but code should also handle them safely with guard clauses:
function sendEmail(user) {
if (!user?.email) {
console.(, user);
;
}
}
Common Mistakes
Expecting JSON.stringify() to handle every object
JSON.stringify() works well for JSON-like data, but it cannot serialize circular references.
const account = {};
account.self = account;
JSON.stringify(account); // TypeError: Converting circular structure to JSON
Use console.log(account) or console.dir(account) instead.
Assuming JSON.stringify() shows every value
It omits properties whose values are undefined, functions, or symbols when they appear in objects.
const settings = {
theme: "dark",
onSave() {},
temporary: undefined
};
console.log(JSON.stringify(settings));
// {"theme":"dark"}
Use console inspection or Object.entries() when those values matter.
Comparisons
| Tool | Best for | Output and limitations |
|---|---|---|
console.log(object) | Everyday debugging | Displays the object in the console, often interactively. |
console.dir(object) | Inspecting an object as properties | Especially useful in browser developer tools. |
Object.keys(object) | Getting property names | Returns only own enumerable keys. |
Object.values(object) | Getting values | Returns only own enumerable values. |
Object.entries(object) | Looping through names and values | Returns [key, value] pairs. |
JSON.stringify(object, null, 2) |
Cheat Sheet
// General object inspection
console.log(object);
console.dir(object);
// Property names, values, and pairs
Object.keys(object);
Object.values(object);
Object.entries(object);
// Print each key and value
for (const [key, value] of Object.entries(object)) {
console.log(key, value);
}
// Readable JSON text; suitable only for JSON-compatible data
console.log(JSON.stringify(object, null, 2));
// Tabular output
console.table(arrayOfObjects);
Object.keys,Object.values, andObject.entriesreturn own enumerable properties.JSON.stringify()cannot serialize circular references.
FAQ
What is JavaScript's equivalent of PHP print_r()?
For debugging, console.log(object) is the closest everyday equivalent. console.dir(object) is also useful for an object-property view.
How do I print every property and value of an object?
Use Object.entries() and loop through its pairs:
for (const [key, value] of Object.entries(object)) {
console.log(key, value);
}
Why does console.log() show an expandable object instead of text?
Developer tools provide an interactive object inspector. This is normally more useful than plain text because nested objects can be expanded.
How can I print an object as formatted JSON?
Use JSON.stringify(object, null, 2). It produces indented JSON, but only for JSON-compatible data without circular references.
Why is a property missing from JSON.stringify() output?
Object properties with undefined, function, or symbol values are omitted. Circular references cause an error instead of output.
Mini Project
Description
Create a small order-debugging utility. It receives an order object, checks that required data exists, and prints a readable summary of every available property. This mirrors the kind of diagnostic logging used when investigating checkout or API issues.
Goal
Build a function that safely inspects an order object and logs its properties in a readable form.
Requirements
Use an object containing an order ID, customer name, total, and status.
Create a function that accepts an order object.
Use a guard clause when the order is missing or is not an object.
Print each property name and value with Object.entries().
Also print a formatted JSON representation when possible.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Add Rows to a Pandas DataFrame in Python
Learn how to add rows to a Pandas DataFrame, why repeated row appends are slow, and when to use loc, concat, or record lists.
Call a Function by Name in a Python Module
Learn how to call a function by name in a Python module using strings, getattr, and safe patterns for dynamic function dispatch.