Is This Possible Within This Switch Statement?


#1

Continuing to push the envelope here…due to plain ol’ ignorance of the technology:

function newAge () {

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

	switch (true) {
		case (val2 < 0):
			alert("Error: Negative Number");
			break;
		case (val === "" || val === " "):
			alert("Hey!  Play along!");
			break;
		case (isNaN(val)):
			alert("Numerals only, please!");
			newAge();
			break;        
		case (val2 === 21):
			alert("Happy 21st Birthday!!");
			break;
		case ((val2 === parseInt(Math.sqrt(val2)) * parseInt(Math.sqrt(val2))) && (val2 !== 0 && val2 !== 1)):
			alert("Perfect Square! " + "(" + parseInt(Math.pow(Math.sqrt(val2), 2)) + " = " + Math.sqrt(val2) + " * " + Math.sqrt(val2) + ")");
			break;
		case (val2 % 2 !== 0):
			alert("Your age is 'Odd!'");
			break;
		default:
			alert(val2 + " is a nice age to be. ^_^");
	}
}

newAge();

That works fine…but I’m interested in the case of isNaN(val); right now, that works like this:

  1. If initial input is NaN, then user is alerted to the fact
  2. Function is rerun

So I’m curious whether this is possible instead:

  1. If initial input is NaN, user is prompted to enter a number
  2. Function is rerun with this new input in mind

I mean, given the “design” of the code as it currently stands – that is, without a drastic redesign of the logic…I’m curious whether there’s some syntax or strategy in JavaScript that could allow for the alternative I’ve outlined (understanding, of course, that “drastic” is pretty much subjective).

Thank you all again!!


#2

Your isNaN case does not need a break. Yes, it is okay to call the same function again.

Instead of using alert(), use return and log the return value.

Complex expressions should be shunted off to a helper function, not written into a case parameter.

function is_perfect(x) {
    return ! (Math.sqrt(x)) % 1
}
    case is_perfect(val2):
        return `Perfect Square! ${val2) = ${parseInt(val2 ** 0.5)} * ${parseInt(val2 ** 0.5))`
console.log(newAge());

This case will never be true since input has been cast to integer. Any non-numeral inputs (including empty string or space) will cast to NaN.


#3

I didn’t think so at first also – but upon testing, it turned out that strange behavior results without a break! Can you imagine why? I was wondering whether to ask about that, too…

Well, the thing is, I’m not using the browser console but an online editor…I dislike using the console for various reasons.

No, actually – it works just as I’d reasoned it would (for a change!)…try it!

Hmm, thanks…erm, lemme digest that first – I see you’ve got some String Literals but that’s all I know and can’t really make out the logic without some further reading first…uh, be back in a relative jiff…


#4

Right… Forgot the return value. Try,

return newAge();
 > parseInt("")
<- NaN
 >

String Literals are the wonder drug of ES. I love them, and try to use them as much as possible for interpolation. Now that backticks are valid quotes, there are very few situations that absolutely call for the old style quotes. We can use the ticks on all strings, not just template literals.

As for the logic, the square root of a perfect square is an integer. That logic returns true if the root is an integer, else false.

3.14 % 1  =>  0.14  // so not an integer.

Then learn how to manipulate the DOM so you can insert the result into the browser page.

<div id="output"></div>
const output = document.querySelector("#output");

Above we cache the page node. This is a one-time operation that permits us to dynamically update the text content of the DIV.

output.textContent = newAge();

Still, console.log() is our friend in so many ways. Don’t shy away from it.


#5

Thanks, that works!

> parseInt("") <- NaN

Well, to be perfectly precise, that’s not exactly what I did in my code, which is, again,

var val = prompt("What is your age?");
	var val2 = parseInt(val);
.
.
.
case (val === "" || val === " "):
			alert("Hey!  Play along!");
			break;

Now here’s the mystery about that: I need to do a var val2 = parseInt(val) even though I’m evaluating plain ol’ “vanilla” val and not val2 – in order for case (val === “” || val === " ") to work, I actually need val2 = parseInt(val) for some strange reason!!!

Can you imagine why?? I sure can’t…

Yes, I’m gonna incorporate that into my “code design” – my workflow, which is to say my very thinking…still stuck on all ‘em ol’ JS tutorials with the document.write(“whatever” + someVariable + " space and whatever some more" + " (" + Some.method(anotherVariable)) + “)”); type of concatenation and interpolation!!

Thanks. I’m gonna have a look-over soon.

I’m too busy to be dabbling in HTML right now…just wanna see if the JS works!! Besides, these online JS editors handle the HTML for me. (Rest assured, I can’t wait to incorporate JS and HTML and CSS…once I got my JS up to par with my HTML and my CSS!!)

No doubt it’s preferred for a reason…many reasons, I’m sure – just none of which apply to me yet. Just for starters, I find it positively annoying to have to perform keyboard acrobatics, mild as they are (though they’re worse on a laptop keyboard, even a full set like on my 17-incher [screen]), every time I wanna do a carriage return!!


#6

Oops! Didn’t look that closely being so bent of other things.

Today JS is more secure than of old. document.write() permits code injection so was one of the first methods to be shelved (though it still works). It’s been out of fashion for at least a decade now. Definitely don’t use it on a site facing the web.


#7

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