Md Nazmul Hossain
Md Nazmul Hossain

Reputation: 2933

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?

Upvotes: 1

Views: 6368

Answers (8)

There's a magic way with JS that kinda breaks your brain but it works

var numValue = 6
var finalValue = `Hello X${numValue > 5 && `, ${numValue} is your promo code` || ''}`

console.log(finalValue)
// Hello X, 6 is your promo code

Where if the numValue=5

const numValue = 5
const finalValue = `Hello X${numValue > 5 && `, ${numValue} is your promo code` || ''}`

console.log(finalValue)
// Hello X

So in case numValue > 5 is true the returned value be ${numValue} is your promo code but if it's false then we need to add the || '' to return an empty string or you will have false in your string.

It's not a clean solution but it's a solution to consider

But for your own benefit and others when reading the code the conventional ways are better

Example:

const n = 6
let fv = "Hello X"

fv += n > 5 ? `, ${n} is your promo code` : ''

console.log(fv)
// Hello X, 6 is your promo code

Or the other ways suggested above altho some of those examples look like an overkill

GLHF :)

Upvotes: 0

Ar26
Ar26

Reputation: 1109

I like to use the Template literals syntax

For example: `${data > 5 ? "Hello x, 6 is your promo code" : "Hello x"}``

Upvotes: 0

Jose Paredes
Jose Paredes

Reputation: 4090

I will say, it's a simple ternary operator

var data = 6,
    minVal = 5;

var promo = data > minVal ? "Hello x, " + data + " is your promo code" : 'Hello x';

console.log(promo);

Upvotes: 1

halim
halim

Reputation: 211

document.write(data > 5? "Hello x, 6 is your promo code" : "Hello x");

Upvotes: 3

Fadhly Permata
Fadhly Permata

Reputation: 1686

Try this:

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

Upvotes: 3

salih0vicX
salih0vicX

Reputation: 1373

    var x=3;
    alert('Hello' + ((typeof(x) =='undefined' || x<5) ? ' x, ' : ', ' +x + ' is your promo code'));

Upvotes: 1

Bartłomiej Gładys
Bartłomiej Gładys

Reputation: 4615

try this:

(data>5) ? "Hello x," +6+" is your promo code" : "Hello x

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386730

You could use a conditional (ternary) operator

condition ? expr1 : expr2 

The conditional (ternary) operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if statement.

var data = 6,
    promo = data > 5 ? "Hello x, 6 is your promo code" : 'Hello x';

console.log(promo);

Upvotes: 2

Related Questions