How to Use a Ternary Operator in an Object Key’s Value in JavaScript 🔑

Omar Shishani
2 min readJan 12, 2021

--

In this post I only want to show the formatting for a nested ternary operator, because this formatting took me a while to figure out.

For my application, I used a function that took two arguments, and each one decided the value of a respective ternary inside of the function. See the example below:

const victoryAxisStyle = (axis, nightMode) => (nightMode ?   {    grid: {        //TERNARY SHOULD NOT BE WRAPPED IN BRACKETS OR PARENTHESES:
stroke: axis === 'y' ? lightGrey : darkGrey,
strokeDasharray: '7' } } : { grid: { stroke: axis === 'y' ? darkGrey : lightGrey, strokeDasharray: '7'
}
})

React JSX

The problem I had was writing a ternary operator as an object key. I thought that the operator needed to be wrapped in brackets, but this is not the case when the ternary is nested inside the object, and is simply deciding the object’s key.

Love Locks By Markus Spiske on Unsplash

Foggy Mountain Summit by v2osk on Unsplash

--

--

Omar Shishani
Omar Shishani

Written by Omar Shishani

Hi! I am a React developer who loves technology and learning new things in all different fields. https://omarshishani.com

No responses yet