+ 2

Hello Can I use comparison operators after a case? Or switch only supports a direct comparison with each case of identical type?

var age = 11; switch(age){ case age <=12: alert('You are child'); break; ... }

16th Aug 2021, 11:09 PM
Osmel Perez Milan
Osmel Perez Milan - avatar
3 Answers
+ 6
Yes, you can use comparison operators. But, switch has to be true for age to work. switch(true)
17th Aug 2021, 2:20 AM
Simba
Simba - avatar
+ 5
var age = 12; switch(true){ case age <= 12: alert('You are a child'); break; case age < 18: alert('You are a teenager'); break; case age >= 18: alert('You are an adult'); break; default: alert('You don\'t insert your age') }
17th Aug 2021, 2:52 PM
Simba
Simba - avatar
+ 1
I try but it doesn't work. Please review my code and suggest the solution Code: var age = 12; switch(age){ case age <= 12: alert('You are a child'); break; case age < 18: alert('You are a teenager'); break; case age >= 18: alert('You are an adult'); break; default: alert('You don\'t insert your age') }
17th Aug 2021, 2:43 PM
Osmel Perez Milan
Osmel Perez Milan - avatar