Nested Ternary Operator

Viewed 62

Having some issue with nested ternary :

I have code :

var genericName = Beauty;

setTitle = (!empty(shopOnline) ? shopOnline + ' | ' : '') 
    + (!empty(productName) ? productName + ' | ' : '') 
    + genericName;

I want scenario like:

  1. if genericName is not empty - Shop Online | Product Name | Generic Name
  2. if genericName is empty - Shop Online | Product Name

Currently I am getting the output of my code (if genericName is empty) - Shop Online | Product Name |

How we can add the nested ternary operator to remove " | " if genericName is empty after Product Name ( (!empty(productName) ? productName + ' | ' : '') )

1 Answers

Using filter() and join()

[shopOnline, productName, genericName].filter(Boolean).join(' | ')

Here Boolean function is given as a callback to filter out the falsy values like 0, -0, null, false, NaN, undefined, ''

You can also use your empty() as filter's callback

[shopOnline, productName, genericName].filter(i => !empty(i)).join(' | ')
Related