DEV Community

Berra
Berra

Posted on

Debugging with console.log

A 🔥-tip when debugging with console.log. I find this very useful in react/jsx code.

You can use parentheses pretty much anywhere in javascript to evaluate expressions. The “returned” value is the last one evaluated. So for example:

console.log( ("a", "b", "c") )
Enter fullscreen mode Exit fullscreen mode

Will only log "c" to the console.

This is very useful in JSX since we usually do not wan’t to put javascript expressions everywhere.

Consider this example:

<InputElement 
  options={items.map(item => item?.attributes?.title)} 
  value={myValue} 
/>
Enter fullscreen mode Exit fullscreen mode

If I wanted to log out the item element inside my options map function. Must I really refactor it with curly braces and explicit return? No - you don’t.

<InputElement 
  options={items.map(
    item => (console.log(item), item?.attributes?.title),
  )} 
  value={value} 
/>
Enter fullscreen mode Exit fullscreen mode

Let’s do it with the value as well!

<InputElement 
  options={items.map(
    item => (console.log(item), item?.attributes?.title),
  )} 
  value={(console.log({value}), value)} 
/>
Enter fullscreen mode Exit fullscreen mode

Notice the curly braces inside the console.log function. This will print out the following to the console. Making it easier to read.

{ value: "<the value>" }
Enter fullscreen mode Exit fullscreen mode

So, what is going on?

This is actually the comma operator we're using. Read more about the details about that here: mdn web docs

Hope you found this useful.

Until next time!

Top comments (0)