Md. Nazmul Hossain Bilash Md. Nazmul Hossain Bilash - 1 month ago 7
Javascript Question

how to concat string with dynamic value if that value exists

Suppose I have a variable

data
:

var data = 6;


If we have
data
value and it's greater than 5 then the output should be:

"Hello x, 6 is your promo code"


If we don't have a
data
value, or the value is less than 5 then the output should be:

"Hello x"


How can I do this with a single line of JavaScript?

Answer

Try this:

var numb = 12;
var msg = "Hello x" + (numb > 5 ? (', ' + numb + ' is your promo code') : '');
console.log(msg);

Comments