javascriptif-statementconditional-statementsor-operator

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


Solution

  • i think this will work for you :

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