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
I was trying to use switch in this case but is not working either, don’t know what is wron, with the if statement is working, but with switch is not:
//creating a function to check the age:
const lifePhase = age => {
//using switch
switch(age){
case age < 0 || case age > 140:
return 'This is not a valid age';
break;
case age <= 3:
return 'baby';
break;
case age <= 12:
return 'child';
break;
case age <= 19:
return 'teen';
break;
case age <= 64:
return 'adult';
break;
case age <= 140:
return 'senior citizen';
break;
}
}
//this is the if statement:
if (age < 0 || age>140){
return 'This is not a valid age'
}else if(age<=3){
return 'baby';
} else if(age<=12){
return 'child';
} else if(age<=19){
return 'teen';
} else if(age<=64){
return 'adult';
} else if(age<=140){
return 'senior citizen';
}
}
console.log(lifePhase(5)) //should print 'child'
console.log(lifePhase(18)) //should print 'teen'
console.log(lifePhase(0)) //should print 'baby'
console.log(lifePhase(158)) //should print 'This is not a valid age'
console.log(lifePhase(200)) //should print 'This is not a valid age'
can somebody take a look?
Switch statements don’t work that way, they only check whether the value is equal to to case, but not < and not >
So it you want something to happen for a specific age,
you might do
switch(age) {
case 0:
return 'infant'; break;
case 1:
return 'baby'; break;
case 2:
return 'crawler'; break;
case 3:
return 'toddler'; break;
}
In your code, you can change switch(age)
to switch(true)
so that the first case that evaluates to true
runs.
1 Like
perfect thank you for your help.