How can I replace "if-else" with "switch" | JavaScript

Hi everyone,
How can I use “switch” to replace the “if-else” statement here? I commented my original if-else statement and wrote the wrong switch below. I am really confused since I followed the class example but still error.

Thank you,
Sunny

let userName ='';
/*if  (userName){
  console.log(`Hello, ${userName}!`)
} else{
  console.log('Hello!')
}*/

switch(userName){
  case true:
  console.log(`Hello, ${userName}!`)
  break;
  case false:
  console.log('Hello!')
  break;
}

switch does a equality comparison. So you can’t use switch to test if a value is truthy.

I would advise against using switch here. There might be some hack-y solution, but you do not want to go there

Thank you! It is helpful~

Actually, you can use a switch statement to check for truthiness. Just write:

let userName ='';

switch(!!userName){
  case true:
  console.log(`Hello, ${userName}!`)
  break;
  case false:
  console.log('Hello!')
  break;
}

This isn’t checking for the value of the userName variable, but the boolean value of it. The NOT operator negates the value of a boolean, right? So NOT NOT basically converts a value to its opposite boolean, and then converts it back to its original boolean value

3 Likes

Nice one, hadn’t thought of that

But I would still prefer if/else here

3 Likes