How to inspect a variable while debugging
Short answer
Wrap variables in curly braces: then the console shows their names together with the values:
const user = 'Anna';
const total = 42;
console.log({ user, total });Output:
{
"user": "Anna",
"total": 42
}Nested objects
JSON.stringify() with an indent shows the whole object, including deep levels:
const order = { id: 7, customer: { name: 'Anna', address: { city: 'Rome' } } };
console.log(JSON.stringify(order, null, 2));Output:
{
"id": 7,
"customer": {
"name": "Anna",
"address": {
"city": "Rome"
}
}
}A table
In the browser console and in Node.js, console.table() shows an array of objects as a table:
console.table([
{ name: 'Anna', age: 30 },
{ name: 'Oleg', age: 25 },
]);A breakpoint
The debugger statement stops the code when the browser developer tools are open. There you can look at all variables:
function calculateTotal(items) {
debugger;
return items.reduce((sum, item) => sum + item.price, 0);
}Common mistake
The browser console shows objects as they are at the moment you expand them, not at the moment of logging. If the object changes later, you see the new values. Log a copy to see the old state:
const cart = { items: 1 };
console.log(JSON.parse(JSON.stringify(cart)));
cart.items = 5;Output:
{
"items": 1
}Functions used in this recipe
- console.log — Prints values to the console.
- JSON.stringify — Converts a value to a JSON string.
- console.table — Shows an array of objects as a table in the browser console.