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

Love locks on fence.

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'
    }
  }
)

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.

Foggy mountain summit.

Love Locks By Markus Spiske on Unsplash

Foggy Mountain Summit by v2osk on Unsplash

Subscribe to new blog posts