Search code examples
javascriptternary-operatorcode-duplicationmethod-chaining

JS – Ternary operator to avoid excessive chaining in a conditional. Is it possible?


condition ?
    domElement.classList.add('show') :
    domElement.classList.remove('show');

The above code works, but the DOM-variable and classList are explicitly typed twice. Is there any way to use a ternary to only put the differentiating parts of the chain in their respective true/false clause?

I'm thinking something like:

domElement.classList condition ? .add('show') : .remove('show');

Any and all input is greatly appreciated.


Solution

  • domElement.classList[condition ? 'add' : 'remove']('show')
    

    Better though:

    domElement.classList.toggle('show', condition)
    

    See https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#Methods.