Switch/case instead of ternary operator in 8 ball exercise

Hello,

Just seeing if anyone has an understanding of this for the eight ball exercise. If anyone thinks this is interesting or understands it that would be great!

To understand conditionals really well I thought I could put a switch/case statement or an if statement in the exercises instead of a ternary operator. I wanted to check the case as true, since the variable had a defined string of my name. So the variable is ‘truthy’. Yet when I ran this it wouldn’t work. I want to understand why so I understand ‘truthy’ and ‘falsy’ and how they evaluate.

This is the code example. Even though username is truthy, the default is what prints to the console.log

let userName = ‘Ryan’;

switch(userName) {
case true :
(console.log(Hello ${userName}!));
break;
default : (console.log(‘Hello!’));
}
Likewise an if statement also doesn’t work as anticipated

let userName = ‘Ryan’;

if (userName === true) {
console.log(Hello ${userName}!);
}
else {
console.log(‘Hello!’);
}

What is difficult is that I thought that ternary operators just worked like this, that the ternary operator would check if something were truthy or falsy. So this ternary operator works, but I don’t understand why this does and the above examples don’t

let userName = ‘Ryan’;

userName ? (console.log(Hello ${userName}!)) :
(console.log(‘Hello!’));

This is magic 8 ball exercise:
https://www.codecademy.com/courses/introduction-to-javascript/projects/magic-eight-ball-1

Thanks for any comments!

You must select a tag to post in this category. Please find the tag relating to the section of the course you are on E.g. loops, learn-compatibility

When you ask a question, don’t forget to include a link to the exercise or project you’re dealing with!

If you want to have the best chances of getting a useful answer quickly, make sure you follow our guidelines about how to ask a good question. That way you’ll be helping everyone – helping people to answer your question and helping others who are stuck to find the question and answer! :slight_smile:

You know what? I actually just found the answer. I don’t have to set it as equal to true, just use the variable name.

Important detail!

So these work like this!

let userName = ‘Ryan’;

if (userName) {
console.log(Hello ${userName}!);
}
else {
console.log(‘Hello!’);
}

switch(userName) {
case userName :
(console.log(Hello ${userName}!));
break;
default : (console.log(‘Hello!’));
}

1 Like

When using switch, Js is doing the comparison for you.

so for example:

switch(userName) {
   case 'Ryan':
     console.log('welcome Ryan');
     break;
  case 'Sam':
    console.log('Yo Sam');
    break;
}

so we can have different greats for different users names.