+ 1
age is greater than 18, alert "old enough", otherwise "too young"
how to use switch statement along with ternary operator for above mentioned alert
6 ответов
+ 3
var result = age > 18 ? alert("Old enough.") : alert("Too Young");
^There ya go. Switch statement is best suited for very specific values; a case. For this, especially since you're dealing with ranges, just use a simple IF/ELSE (or ternary) statement.
+ 3
If it's simply curiosity, then yes you can use a switch if you wanted. However, it's not efficient and is at the cost of a lot of additional coding to accomplish the same thing. It may be useful if you wanted to use the ternary to get your ranges sorted out first, and then use the switch to execute a block of code rather than simply alerting.
https://code.sololearn.com/W05RxH0rO250/#js
var age = 18;
var isOld = false;
// EXAMPLE #1 - ternary operator
var result = age >= 18 ? alert("Old enough.") : alert("Too young.");
// EXAMPLE #2 - switch statement
var result2 = age >= 18 ? isOld = true: isOld = false;
switch(result2) {
case true:
alert("Old enough.");
break;
case false:
alert("Too young.");
breal;
}
+ 2
I know what might happen... ALERT 11 IS WAY TOO YOUNG GET OUT OF HERE
+ 2
Ok, I over exaggerated a little
+ 1
yes already done that. i was just curious to know whether is there anyway to do that or not. Thank you Jakob
+ 1
thank you so much.