Conditional in Switch Statement Not Working


#1

It appears to be possible to implement conditionals in Switch statements – but the following isn’t working:

var val = prompt("What is your age?");

switch (true) {
	case (val < 0):
		alert("Error: Negative Number");
		break;
	case (val===4||val===9||val===16||val===25||val===36||val===49||val===64||val===81||val===100):
		alert("Perfect Square!");
		break;
	case (val === 21):
		alert("Happy 21st Birthday!!");
		break;
	case (val % 2 !== 0):
		alert("Your age is 'Odd!'");
		break;
	default:
		alert(val + " is a nice age to be. ^_^");
}

Only the first, second-to-last, and last (default) cases are ever evaluated for some reason; commenting out

case (val < 0):
		alert("Error: Negative Number");
		break;

and/or

case (val===4||val===9||val===16||val===25||val===36||val===49||val===64||val===81||val===100):
		alert("Perfect Square!");
		break;

and/or

case (val % 2 !== 0):
		alert("Your age is 'Odd!'");
		break;

doesn’t work (doesn’t get any other case to evaluate) in any combination…what’s the problem, please??

THANK YOU KINDLY!!!


#2

Set val to a number instead of a string
…though js might not care, I should run it myself >.>


#3

THAT MAKES PERFECT SENSE!!!

THANKS SO MUCH!!!

Boy, I feel like I’m playing at being a lawyer when trying to program, what with all these “fine-print gotchas”…!!

Adding a

var val2 = parseInt(val);

and adjusting accordingly, such as

case (val2 === 21):

does the trick!!

Thanks so much again…


#4

Uh. Yeah. The equal/equal type operator definitely cares.
I wouldn’t say gotchas, but you should know exactly what things do to leverage them
JS might have some gotchas though, yeah, it has some “helpful” features that mostly just make it difficult to know if you got it right


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.