1

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?

cjhveal
  • 5,668
  • 2
  • 28
  • 38
Md Nazmul Hossain
  • 2,768
  • 5
  • 26
  • 49

8 Answers8

3

Try this:

var numb = 12;
var msg = "Hello x" + (numb > 5 ? (', ' + numb + ' is your promo code') : '');
console.log(msg);
Fadhly Permata
  • 1,686
  • 13
  • 26
3
document.write(data > 5? "Hello x, 6 is your promo code" : "Hello x");
halim
  • 211
  • 1
  • 10
2

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

try this:

(data>5) ? "Hello x," +6+" is your promo code" : "Hello x
Bartłomiej Gładys
  • 4,525
  • 1
  • 14
  • 24
1

    var x=3;
    alert('Hello' + ((typeof(x) =='undefined' || x<5) ? ' x, ' : ', ' +x + ' is your promo code'));
salih0vicX
  • 1,363
  • 1
  • 8
  • 9
  • var x=32; alert('Hello' + ((typeof(x) =='undefined' || x<5) ? ' x, ' : ', your promo code is '+x)); It also ensures that variable x is declared ... If it is not declared, the result would be 'Hello x, ' – salih0vicX Sep 21 '16 at 07:24
1

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);
Jose Paredes
  • 3,882
  • 3
  • 26
  • 50
0

I like to use the Template literals syntax

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

Ar26
  • 949
  • 1
  • 12
  • 29
0

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 :)