+ 1

While solving switch problems I didn’t find any problem in my code.But its showing default values only.Whats the problem here?

var age=prompt("Enter You age"); switch(age){ case age<=12: document. write("You are a child"); break; case age<=18: document. write("You are a teenager"); break; case age<=40: document. write("You are a middle aged person"); break; case age>40: document.write("You are an old guy"); alert("Eat well,Sleep well,Take care❤️"); break; default: alert("You did not enter your age"); document. write("As you did not enter your age I want to ask a question.Are you alive?") } I didn’t find any problem out there.Help me to solve this problem🙂

11th Jul 2021, 3:41 PM
Tanjid Ahsan Riad
Tanjid Ahsan Riad - avatar
4 odpowiedzi
+ 7
Switch has to be true for prompt to work. switch(true)
11th Jul 2021, 3:44 PM
Simba
Simba - avatar
+ 4
Tanjid Ahsan Riad Ternary operators would be much preferable to using a switch statement when the value used for case matching is a boolean. Here's a rough alternative of your code. ---- //Prepare output const type = age <= 12 ? "a child" : age <= 18 ? "a teenager" : age <= 40 ? "a middle aged person" : age > 40 ? "an old guy" : "unknown" const response = type == "unknown" ? "As you did not enter your age I want to ask a question.Are you alive?" : `You are ${type}` //Display the results if(type == "unknown") alert("You did not enter your age") document.write(response) if(age > 40) alert("Eat well,Sleep well,Take care❤️") ---- Although I've not tested this, it should match the original code. This code, however, controls the flow such that the output is fully prepared before rendered. This minimizes duplicate code and makes the code less brittle. NOTE: I'm only working with the given example. Otherwise, I would have abstracted this further. 😉
12th Jul 2021, 4:19 AM
David Carroll
David Carroll - avatar
+ 1
Solved
11th Jul 2021, 3:47 PM
Tanjid Ahsan Riad
Tanjid Ahsan Riad - avatar
+ 1
in javascript 'switch' is intended to take a variable identifier as "argument" (inside parenthesis), and check if it is equals to case operands... it is not intended to work with condition as 'case' operand ^^ anyway, setting true (or false) as switch argument allow you to make it work with conditon as case operand in a tricky way: boolean value is compared to result of conditions... ;P that's the first time I see switch used by this way: that's a cool hack to remember to be able to use ranges or any conditional as case operands :D
11th Jul 2021, 9:07 PM
visph
visph - avatar