coolps811
coolps811

Reputation: 323

How to check for falsey string value when concatenating?

In the following examples both ex1 & ex2 variables will render an empty string with a space and not a falsy value. Whereas ex3 will be falsy and render the right side of the || operator. How can I test for empty string in the first two examples without doing an if statement?

let var1 = '';
let var2 = '';
let ex1 = `${var1} ${var2}` || "Is Falsy";
let ex2 = var1 + ' ' + var2 || "Is Falsy";
let ex3 = var1 || "Is Falsy";

Upvotes: -1

Views: 79

Answers (5)

Said Taher
Said Taher

Reputation: 51

i think this will work for you :

let ex2 = var1 || var2 || "Is Falsy";

Upvotes: 1

Pran Sukh
Pran Sukh

Reputation: 545

Use ternary operators:

let var1 = '';
let var2 = '';
let ex1 = (`${var1} ${var2}`).trim().length > 0 ? `${var1} ${var2}` : "Is Falsy";
let ex2 = (var1 + ' ' + var2).trim().length > 0 ? var1 + ' ' + var2 : "Is Falsy";
let ex3 = var1.trim().length > 0 ? var1 : "Is Falsy";

Upvotes: 0

Tomer Alony
Tomer Alony

Reputation: 34

You can try this typing method:

const str = "not empty"

console.log(!str); // will be false, to check if a string is empty
console.log(!!str); // will be true, to check if a string is not empty

Upvotes: -1

Tushar Shahi
Tushar Shahi

Reputation: 20626

If you are okay with using conditional operators, this can be done with the help of trim() :

let var1 = '';
let var2 = '';
let ex1 = (`${var1} ${var2}`).trim()/length > 0 ? `${var1} ${var2}` : "Is Falsy";
let ex2 = (var1 + ' ' + var2).trim().length > 0 ? var1 + ' ' + var2 : "Is Falsy";
let ex3 = var1 || "Is Falsy";
console.log(ex1);
console.log(ex2);
console.log(ex3);

Upvotes: 0

Jamiec
Jamiec

Reputation: 136164

Are ternary operators acceptable?

let ex1 = var1 && var2 ? `${var1} ${var2}` : "Is Falsy";

Upvotes: 0

Related Questions