Pipes instead of if else problem

var userName = “”;

userName ? console.log("Hello, " + ${userName}) : console.log(“Hello!”);

username = console.log("Hello, " + ${userName}) || console.log(“Hello!”);

Hi so the top line works as a ternary if else, I tried to do a similar thing using pipes but its doesnt work, it logs both hellos instead of just the “Hello”.


The first statement is equivalent to:

if (userName) {
    console.log(`Hello, ${userName}`); 
} else {

Since you have initialized userName as the empty string "", so userName is Falsy and only the else block is executed.

In the second statement,

username = console.log(`Hello, ${userName}`) || console.log("Hello!");

you are using the || operator to assign a value to the username variable. The first operand i.e.

console.log(`Hello, ${userName}`)

is evaluated. Evaluation causes the string "Hello, " to be printed. But, the return value of a console.log() statement is undefined (see documentation). Since evaluation of the first operand results in a falsy value, so then the second operand is evaluated. This causes "Hello!" to be printed, but again the return value of console.log() is undefined. So, undefined is assigned to the variable username.

1 Like