Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary inside string literals

Been trying to add a conditionals inside a template strings. I am unable to do it. I have two strings say t1 and t2, and when t2 is undefined or empty just display t1 and when t2 is present append that t2 inside parentheses along with t1

let t1= "hey";
let t2 = "there";
//need the output something like hey(there) when there t2 is present. when it is null or undefined or empty just show hey 

//Have tried the below but it is not working
console.log(`${t2} ${t1} ? ${t1}(${t2}): ${t1}`)
like image 654
joy08 Avatar asked Jun 15 '26 16:06

joy08


2 Answers

The ternary should be done inside of the ${} expression as follows:

let t1 = "hey";
let t2 = "there";
console.log(`${t1}${t2 ? `(${t2})` : ''}`);

An explanation of the code above is as follows:

  1. Since you've specified that the prefix "hey" should be specified regardless of whether you've defined t2 or not, there's no need to include it in the ternary expression.
  2. The next part of the code is an inlined ternary operator that checks if t2 is truthy.

    • If it is truthy, the first part of the ternary operator is executed. In other words, the ternary operator will return (${t2}). And since this is another template literal, this will be evaluated with the substitution of the t2 variable into the template expression.
    • If it isn't truthy, the second part of the ternary operator is executed, which is an empty string.

Note that you can have template literals inside template literals. See the Template Literals documentation on MDN for more info.

like image 54
Edric Avatar answered Jun 17 '26 06:06

Edric


Expression can only be written inside {} when using string literals. You need to use nested template strings here

let t1= "hey";
let t2 = "there";
console.log(`${t1}${t2 ? `(${t2})` : ''}`)
like image 31
Maheer Ali Avatar answered Jun 17 '26 04:06

Maheer Ali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!