Logging an Object in JavaScript
- 3 minutes read - 461 wordsWhen printing a JavaScript value to the console, I suggest using an object literal over the raw value.
// Okay
console.log(response)
// Better
console.log({ response })
It’s a little thing that over time has a big benefit. In this post, I’ll explain this technique and describe why I find it useful.
First Iteration: The Raw Value
Imagine you have a value assigned to the variable response
, and you want to
know its value. Here’s how you might print it to the console, with
console.log.
console.log(response)
This is what 99% of devs (including me, often) are going to do, and it’s fine. But since you’re reading this post, you might wonder– can we improve upon it?
One issue with logging the raw value is that it might be an empty string,
null
, or undefined
. That’s going to be a tiny blip in your console,
possibly hidden among other logs and errors, that can be easy to miss. Missing
a printed value and making an incorrect assertion about what happened is a
classic debugging mistake.
Another issue: if you do this more than once in the same debugging session, and
multiple of your printed values could be empty strings, null
, or undefined
,
you’re pretty much guessing which is which.
Second Iteration: A Label
A slightly better technique is printing with a label:
console.log("The response is: ", response)
This prints The response is:
and the response. The result will be labeled
and thus easier to find and read. But, you have to type this little helper
every time or use some kind of function or text editor mapping to get it.
Final Iteration: An Object
Okay, here’s the best choice!
console.log({ response })
Why is this ideal? It wins because it prints an object with the key response
and the value of response
. Here are some examples:
// String
{ response: "hello" }
// Empty string
{ response: '' }
// Undefined
{ response: undefined }
// Null
{ response: null }
// Boolean
{ response: false }
// Object
{ response: { status: 'ok' } }
Logging an object is fast to write, just two more keystrokes than the raw value. It’s easier to see in the console, so you’ll find it and make better assertions about behavior. And, it’s more searchable: type ‘response’, or whatever you have named your variable into your browser console’s search bar, to filter out everything but your log.
Another benefit? You can keep adding to the object and get the same behavior, grouped and labeled.
console.log({ date, dateDisplay, responseCode })
Which could print:
{
date: '2023-08-04',
display: '2023-08-03',
responseCode: 422
}
Your Turn
With this technique, we get fast-to-type, findable, and searchable logs for the cost of just two keystrokes. Try it the next time you’re debugging.