If else statement: correct syntax Vs ternary expressions

Hi!

I’ve been playing around with the 8-ball project to change the sentance structure to account for whether someone puts in a username or not. I’ve been able to make the syntax correct using a ternary expression, but can’t replicate the function using an if… else… statement. Could somebody please let me know where I’m going wrong?

This works fine:

userName ? console.log(${userName}'s question is ${userQuestion}) : console.log(The question is ${userQuestion});

whereas this:

if (userName) {
console.log(${userName}'s question is ${userQuestion});
} else if (userName === undefined) {
console.log(The question is ${userQuestion});
}

Generates output just fine with a username, but doesn’t generate any output when a username is missing.

Thanks!

Hello!

From what I remember of the project, userName is set to ‘’ by default, which means that it isn’t undefined.

Your ternary works because it checks if userName is truthy (so it’s not an empty string) and does an action for both true and false. Your if condition adds extra conditions to that by checking if userName is specifically undefined (which an empty string isn’t).

1 Like

Thanks - makes perfect sense!

It’s not actually an if… else is it? Just an if?

I replaced it with this, which works fine:

if (userName) {
console.log(${userName}'s question is ${userQuestion});
} else {
console.log(The question is ${userQuestion});
}

2 Likes