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") )
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}
/>
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}
/>
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)}
/>
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>" }
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)