-1

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";

coolps811
  • 193
  • 4
  • 11
  • What have you tried so far to solve this on your own? If you already know that an empty string is "falsy" and that `||` would help with that... What would be the next step? – Andreas Oct 05 '21 at 12:23
  • I think you might want to use [`.trim()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim) before checking. – Rojo Oct 05 '21 at 12:53

5 Answers5

1

i think this will work for you :

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

Said Taher
  • 51
  • 3
  • @coolps811 Why is this the accepted answer? `ex2` will be the first non-empty string. If both are not empty the result will be different to `ex2` (or `ex1`) in your question. – Andreas Oct 06 '21 at 07:54
0

Are ternary operators acceptable?

let ex1 = var1 && var2 ? `${var1} ${var2}` : "Is Falsy";
Jamiec
  • 133,658
  • 13
  • 134
  • 193
0

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);
Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
0

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";
Pran Sukh
  • 207
  • 4
  • 12
-1

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