Converting if statement to switch/case - javascript

How can I convert this if statement into switch case? I tried to declare the variable like this:
myAge = parseFloat(prompt("Enter you age: "));
if(myAge <18) {
alert("You cant not vote at this " +myAge);
} else if (myAge >18) {
alert("Vote wisely, you are " +myAge "years old!");
} else {
alert("Invalid age");
}

Give condition if age < 18,
You can't not vote at this age
If age> = 18, You can vote at this age.
Else invalid age.
var myAge = parseFloat(prompt("Enter you age: "));
switch (true) {
case myAge < 18:
alert("You cant not vote at this " + myAge);
break;
case myAge >= 18:
alert("Vote wisely, you are " + myAge + " years old!");
break;
default:
alert("Invalid age");
}

Answering your "how can I convert it to switch" question, you can implement a function which makes C-style comparison and returns -1, 0 or 1 as the result of comparing.
The example below uses a setInterval to emulate multiple different cases. This is only for the example.
function compareTo(a, b) {
if (a < b)
return -1;
if (a > b)
return 1;
return 0;
}
function EvaluateAge() {
// Generate a random age between 10 and 40
var myAge = Math.floor((Math.random() * 30) + 10);
switch (compareTo(myAge, 18)) {
case -1:
console.log(myAge, " less than 18");
break;
case 0:
console.log(myAge, " equal to 18");
break;
case 1:
console.log(myAge, "more than 18");
break;
}
}
// Example only
setInterval(EvaluateAge, 1000);
Another way is to use JS switch ability to use true in switch-condition:
var myAge = 16;
switch (true) {
case myAge < 18:
console.log("less than 18");
break;
case myAge === 18:
console.log("equal to 18");
break;
case myAge > 18:
console.log("more than 18");
break;
}
However, it doesn't look good and it is a good idea to avoid this usage.
Actually, your if looks good and imho you don't need to convert it to switch - it won't increase readability / maintainability of your code.

Not sure why you would want to do this instead of concise if statements, but you can like so:
var myAge = parseFloat(prompt("Enter you age: "));
switch (true) {
case myAge < 18:
alert("You cant not vote at this " + myAge);
break;
case myAge > 18:
alert("Vote wisely, you are " + myAge + " years old!");
break;
default:
alert("Invalid age");
}
Note, that you are not capturing a value of 18 which I'll just assume was intentional but worth pointing out to you and, also, you were missing a + concatenating your second alert so your original example wouldn't even have executed.

Related

Javascript Bitwise Operator not behaving correctly [duplicate]

How can I use a condition inside a switch statement for JavaScript?
In the example below, a case should match when the variable liCount is <= 5 and > 0; however, my code does not work:
switch (liCount) {
case 0:
setLayoutState("start");
var api = $("#UploadList").data("jsp");
api.reinitialise();
break;
case liCount <= 5 && liCount > 0:
setLayoutState("upload1Row");
var api = $("#UploadList").data("jsp");
api.reinitialise();
break;
case liCount <= 10 && liCount > 5:
setLayoutState("upload2Rows");
var api = $("#UploadList").data("jsp");
api.reinitialise();
break;
case liCount > 10:
var api = $("#UploadList").data("jsp");
api.reinitialise();
break;
default:
break;
}
Appreciate any advice!
This works:
switch (true) {
case liCount == 0:
setLayoutState('start');
var api = $('#UploadList').data('jsp');
api.reinitialise();
break;
case liCount<=5 && liCount>0:
setLayoutState('upload1Row');
var api = $('#UploadList').data('jsp');
api.reinitialise();
break;
case liCount<=10 && liCount>5:
setLayoutState('upload2Rows');
var api = $('#UploadList').data('jsp');
api.reinitialise();
break;
case liCount>10:
var api = $('#UploadList').data('jsp');
api.reinitialise();
break;
}
The only thing necessary is switch(true){...} and for your case expressions to evaluate to booleans.
It works because, the value we give to the switch is used as the basis to compare against. Consequently, the case expressions, also evaluating to booleans will determine which case is run. Could also turn this around, and pass switch(false){..} and have the desired expressions evaluate to false instead of true.. but personally prefer dealing with conditions that evaluate to truthyness. However, it does work too, so worth keeping in mind to understand what it is doing.
Eg: if liCount is 3, the first comparison is true === (liCount == 0), meaning the first case is false. The switch then moves on to the next case true === (liCount<=5 && liCount>0). This expression evaluates to true, meaning this case is run, and terminates at the break. I've added parentheses here to make it clearer, but they are optional, depending on the complexity of your expression.
It's pretty simple, and a neat way (if it fits with what you are trying to do) of handling a long series of conditions, where perhaps a long series of ìf() ... else if() ... else if () ... might introduce a lot of visual noise or fragility.
Use with caution, because it is a non-standard pattern, despite being valid code.
You've way overcomplicated that. Write it with if statements instead like this:
if(liCount == 0)
setLayoutState('start');
else if(liCount<=5)
setLayoutState('upload1Row');
else if(liCount<=10)
setLayoutState('upload2Rows');
$('#UploadList').data('jsp').reinitialise();
Or, if ChaosPandion is trying to optimize as much as possible:
setLayoutState(liCount == 0 ? 'start' :
liCount <= 5 ? 'upload1Row' :
liCount <= 10 ? 'upload2Rows' :
null);
$('#UploadList').data('jsp').reinitialise();
You want to use if statements:
if (liCount === 0) {
setLayoutState('start');
} else if (liCount <= 5) {
setLayoutState('upload1Row');
} else if (liCount <= 10) {
setLayoutState('upload2Rows');
}
$('#UploadList').data('jsp').reinitialise();
See dmp's answer below. I'd delete this answer if I could, but it was accepted so this is the next best thing :)
You can't. JS Interpreters require you to compare against the switch statement (e.g. there is no "case when" statement). If you really want to do this, you can just make if(){ .. } else if(){ .. } blocks.
You can use fall-through method in switch case.
const x = 'Welcome';
switch (x) {
case 'Come':
console.log(1)
break;
case 'Welcome':
case 'Wel':
case 'come':
console.log(2)
break;
case 'Wel':
console.log(3)
break;
default:
break;
}
> Result => 2
switch (true) {
case condition0:
...
break;
case condition1:
...
break;
}
will work in JavaScript as long as your conditions return proper boolean values, but it doesn't have many advantages over else if statements.
if the possible values are integers you can bunch up cases.
Otherwise, use ifs.
var api, tem;
switch(liCount){
case 0:
tem= 'start';
break;
case 1: case 2: case 3: case 4: case 5:
tem= 'upload1Row';
break;
case 6: case 7: case 8: case 9: case 10:
tem= 'upload2Rows';
break;
default:
break;
}
if(tem) setLayoutState((tem);
api= $('#UploadList').data('jsp');
api.reinitialise();
That's a case where you should use if clauses.
If that's what you want to do, it would be better to use if statements. For example:
if(liCount == 0){
setLayoutState('start');
}
if(liCount<=5 && liCount>0){
setLayoutState('upload1Row');
}
if(liCount<=10 && liCount>5){
setLayoutState('upload2Rows');
}
var api = $('#UploadList').data('jsp');
api.reinitialise();
Your code does not work because it is not doing what you are expecting it to do. Switch blocks take in a value, and compare each case to the given value, looking for equality. Your comparison value is an integer, but most of your case expressions resolve to a boolean value.
So, for example, say liCount = 2. Your first case will not match, because 2 != 0. Your second case, (liCount<=5 && liCount>0) evaluates to true, but 2 != true, so this case will not match either.
For this reason, as many others have said, you should use a series of if...then...else if blocks to do this.
Notice that we don't pass score to the switch but true. The value we give to the switch is used as the basis to compare against.
The below example shows how we can add conditions in the case: without any if statements.
function getGrade(score) {
let grade;
// Write your code here
switch(true) {
case score >= 0 && score <= 5:
grade = 'F';
break;
case score > 5 && score <= 10:
grade = 'E';
break;
case score > 10 && score <= 15:
grade = 'D';
break;
case score > 15 && score <= 20:
grade = 'C';
break;
case score > 20 && score <= 25:
grade = 'B';
break;
case score > 25 && score <= 30:
grade = 'A';
break;
}
return grade;
}
If you want pass any value in switch statement
and then apply condition on that passing value and
evaluate statement then you have to write switch
statement under an function and pass parameter in that
function and then pass true in switch expression like the
below example.
function numberChecker(num){
let age;
switch(true){
case num >= 0 && num <= 10:
age = "Child";
break;
case num >= 10 && num <= 20:
age = "Teenager";
break;
case num >= 20 && num <= 30:
age = "Young";
break;
default:
age = "Undefined!! Enter Age Between 0 - 30";
break;
}
console.log("WOW You Are " + age);
}
numberChecker(15);
Although in the particular example of the OP's question, switch is not appropriate, there is an example where switch is still appropriate/beneficial, but other evaluation expressions are also required. This can be achieved by using the default clause for the expressions:
switch (foo) {
case 'bar':
// do something
break;
case 'foo':
// do something
break;
... // other plain comparison cases
default:
if (foo.length > 16) {
// something specific
} else if (foo.length < 2) {
// maybe error
} else {
// default action for everything else
}
}

Understanding how the switch statement works in JS - am i missing something?

My understanding of the switch statement in general is that, we have what we term as a 'switch value' and each 'case' in a switch statement indicates what code we run if we find a match with that switch value.
However, observe the code below and explain to me why its invalid/incorrect logic wrt using switch statement:
function getScore() {
var score = prompt("Enter student score: ");
var score = parseInt(score);
showGrade(score);
}
function showGrade(score) {
var grade_bands = ["1st Class", "2nd Class", "3rd Class", "Pass", "Referal", "Fail/Re-Take"];
switch (score) {
case score >= 70:
console.log("Your grade band is " + grade_bands[0]);
break;
case score >= 60:
console.log("Your grade band is " + grade_bands[1]);
break;
case score >= 50:
console.log("Your grade band is " + grade_bands[2]);
break;
case score >= 40:
console.log("Your grade band is " + grade_bands[3]);
break;
case score >= 30:
console.log("Your grade band is " + grade_bands[4]);
break;
case score >= 20:
console.log("Your grade band is " + grade_bands[5]);
break;
}
}
getScore();
The above yields 'undefined' when observed in console.
However now look at the code below if you may, and explain why when we use a bool 'true' inside switch(), the code works:
function getScore() {
var score = prompt("Enter student score: ");
var score = parseInt(score);
showGrade(score);
}
function showGrade(score) {
var grade_bands = ["1st Class", "2nd Class", "3rd Class", "Pass", "Referal", "Fail/Re-Take"];
switch (true) {
case score >= 70:
console.log("Your grade band is " + grade_bands[0]);
break;
case score >= 60:
console.log("Your grade band is " + grade_bands[1]);
break;
case score >= 50:
console.log("Your grade band is " + grade_bands[2]);
break;
case score >= 40:
console.log("Your grade band is " + grade_bands[3]);
break;
case score >= 30:
console.log("Your grade band is " + grade_bands[4]);
break;
case score >= 20:
console.log("Your grade band is " + grade_bands[5]);
break;
}
}
getScore();
Some clarification of where I am over thinking/ under thinking or simply 'not thinking might help here folks.
** UPDATE **
So here is mplungjans code modified so that it takes the value of grade and uses it as an index to output the according 'band' that student obtained. Notice my boolean logic differs to his though. His logic gives incorrect bands as per score. Mine below gives correct band as per score:
var score = prompt("Please enter your score: ");
var score = parseInt(score);
var grade = "";
if (score >= 70) grade = 5;
else if (score >= 60) grade = 4;
else if (score >= 50) grade = 3;
else if (score >= 40) grade = 2;
else if (score >= 30) grade = 1;
else grade = 0;
var grade_bands = ["Fail/Re-Take","Referal","Pass","3rd Class","2nd Class","1st Class"];
console.log("You obtained a " + grade_bands[grade] + " band");
Your switch(true) works but I call it an abuse of the switch since it will take ANY statement that return truthy or falsy
You ACTUALLY want to use a switch against specific values.
You CAN do it like this, but IFs in your case would work MUCH better
const grade_bands = ["1st Class", "2nd Class", "3rd Class", "Pass", "Referal", "Fail/Re-Take"];
function showGrade(score) {
switch (score) {
case 10:
case 11:
...
case 20:
console.log("Your grade band is " + grade_bands[5]);
break;
case 30:
console.log("Your grade band is " + grade_bands[4]);
break;
....
}
}
IFs
if (score <20) grade = 0
else if (score <30) grade = 1
else if (score <40) grade = 2
else if (score <50) grade = 3
else if (score <60) grade = 4
else grade = 5
return ["Fail/Re-Take","Referal","Pass","3rd Class","2nd Class","1st Class"][grade]

Someone could explain what is happening with the code?

I want to guess what type of letter the user types down.
var userLetter = prompt("Enter a letter and I will tell you what type of letter is","Enter here, wish me luck!");
function selectUserLetter(letter) {
var returnType = "NA";
if (userLetter.charCodeAt(0) >= "A".charCodeAt(0) && userLetter.charCodeAt(0) <= "Z".charcodeAt(0)) {
returnType = "U";
}
else if (userLetter.charCodeAt(0) >= "a".charCodeAt(0) && userLetter.charCodeAt(0) <= "z".charcodeAt(0)) {
returnType = "L";
}
else if (userLetter.charCodeAt(0) >= "0".charCodeAt(0) && userLetter.charCodeAt(0) <= "9".charcodeAt(0)) {
returnType = "N";
}
return returnType;
}
switch (selectUserLetter(userLetter)) {
case "U":
document.write("Your letter is Uppercase");
break;
case "L":
document.write("Your letter is Lowercase");
break;
case "N":
document.write("Your letter is a number");
break;
default:
document.write("You typed anything else");
}
In your code, fragments "Z".charcodeAt, "z".charcodeAt(0) and "9".charcodeAt(0) consist of charcodeAt function call. The thing is that JavaScript is case sesitive langauge. So, charcodeAt doesn't exists rather then charCodeAt.

Switch case failing, returns NaN [duplicate]

This question already has answers here:
JavaScript conditional switch statement
(5 answers)
Closed 7 years ago.
I have a bmi calculator and converted the conditionals to a switch statement to make it a bit cleaner. However, now the code is breaking and not causing the var result to be set so it can be displayed.
Any ideas what I am missing here?
JS
$('#calculatebutton').click(function () {
var weight = parseInt($('#weight-lb').val()),
heightInches = parseInt($('#height-ft').val()) + parseInt($('#height-in').val()),
heightsqaured = (heightInches) * (heightInches),
result = ((weight) / (heightsqaured) * 703);
switch(result) {
case (result < 16):
var rating = 'You are severely underweight';
break;
case (result > 16) && (result < 18.5):
var rating = 'You are underweight';
break;
case (result > 18.5) && (result < 25):
var rating = 'You are healthy';
break;
case (result > 25) && (result < 30):
var rating = 'You are overweight';
break;
case (result > 30) && (result < 35):
var rating = 'You are moderately obese';
break;
case (result > 80):
var rating = 'This result seems unlikely, please check that the information you have entered is correct';
break;
}
$('#result').html('Your BMI is ' + result.toFixed(1) + '. ' + rating + '.');
});
JS Fiddle
http://jsfiddle.net/o12xpy2s/
Change:
switch(result) {
...to:
switch(true) {
Your switch cases are all true or false conditions. So set your switch expression switch(expression) to one or the other. Here you're looking for the true condition of the listed cases.

JavaScript: using a condition in switch case

How can I use a condition inside a switch statement for JavaScript?
In the example below, a case should match when the variable liCount is <= 5 and > 0; however, my code does not work:
switch (liCount) {
case 0:
setLayoutState("start");
var api = $("#UploadList").data("jsp");
api.reinitialise();
break;
case liCount <= 5 && liCount > 0:
setLayoutState("upload1Row");
var api = $("#UploadList").data("jsp");
api.reinitialise();
break;
case liCount <= 10 && liCount > 5:
setLayoutState("upload2Rows");
var api = $("#UploadList").data("jsp");
api.reinitialise();
break;
case liCount > 10:
var api = $("#UploadList").data("jsp");
api.reinitialise();
break;
default:
break;
}
Appreciate any advice!
This works:
switch (true) {
case liCount == 0:
setLayoutState('start');
var api = $('#UploadList').data('jsp');
api.reinitialise();
break;
case liCount<=5 && liCount>0:
setLayoutState('upload1Row');
var api = $('#UploadList').data('jsp');
api.reinitialise();
break;
case liCount<=10 && liCount>5:
setLayoutState('upload2Rows');
var api = $('#UploadList').data('jsp');
api.reinitialise();
break;
case liCount>10:
var api = $('#UploadList').data('jsp');
api.reinitialise();
break;
}
The only thing necessary is switch(true){...} and for your case expressions to evaluate to booleans.
It works because, the value we give to the switch is used as the basis to compare against. Consequently, the case expressions, also evaluating to booleans will determine which case is run. Could also turn this around, and pass switch(false){..} and have the desired expressions evaluate to false instead of true.. but personally prefer dealing with conditions that evaluate to truthyness. However, it does work too, so worth keeping in mind to understand what it is doing.
Eg: if liCount is 3, the first comparison is true === (liCount == 0), meaning the first case is false. The switch then moves on to the next case true === (liCount<=5 && liCount>0). This expression evaluates to true, meaning this case is run, and terminates at the break. I've added parentheses here to make it clearer, but they are optional, depending on the complexity of your expression.
It's pretty simple, and a neat way (if it fits with what you are trying to do) of handling a long series of conditions, where perhaps a long series of ìf() ... else if() ... else if () ... might introduce a lot of visual noise or fragility.
Use with caution, because it is a non-standard pattern, despite being valid code.
You've way overcomplicated that. Write it with if statements instead like this:
if(liCount == 0)
setLayoutState('start');
else if(liCount<=5)
setLayoutState('upload1Row');
else if(liCount<=10)
setLayoutState('upload2Rows');
$('#UploadList').data('jsp').reinitialise();
Or, if ChaosPandion is trying to optimize as much as possible:
setLayoutState(liCount == 0 ? 'start' :
liCount <= 5 ? 'upload1Row' :
liCount <= 10 ? 'upload2Rows' :
null);
$('#UploadList').data('jsp').reinitialise();
You want to use if statements:
if (liCount === 0) {
setLayoutState('start');
} else if (liCount <= 5) {
setLayoutState('upload1Row');
} else if (liCount <= 10) {
setLayoutState('upload2Rows');
}
$('#UploadList').data('jsp').reinitialise();
See dmp's answer below. I'd delete this answer if I could, but it was accepted so this is the next best thing :)
You can't. JS Interpreters require you to compare against the switch statement (e.g. there is no "case when" statement). If you really want to do this, you can just make if(){ .. } else if(){ .. } blocks.
You can use fall-through method in switch case.
const x = 'Welcome';
switch (x) {
case 'Come':
console.log(1)
break;
case 'Welcome':
case 'Wel':
case 'come':
console.log(2)
break;
case 'Wel':
console.log(3)
break;
default:
break;
}
> Result => 2
switch (true) {
case condition0:
...
break;
case condition1:
...
break;
}
will work in JavaScript as long as your conditions return proper boolean values, but it doesn't have many advantages over else if statements.
if the possible values are integers you can bunch up cases.
Otherwise, use ifs.
var api, tem;
switch(liCount){
case 0:
tem= 'start';
break;
case 1: case 2: case 3: case 4: case 5:
tem= 'upload1Row';
break;
case 6: case 7: case 8: case 9: case 10:
tem= 'upload2Rows';
break;
default:
break;
}
if(tem) setLayoutState((tem);
api= $('#UploadList').data('jsp');
api.reinitialise();
That's a case where you should use if clauses.
If that's what you want to do, it would be better to use if statements. For example:
if(liCount == 0){
setLayoutState('start');
}
if(liCount<=5 && liCount>0){
setLayoutState('upload1Row');
}
if(liCount<=10 && liCount>5){
setLayoutState('upload2Rows');
}
var api = $('#UploadList').data('jsp');
api.reinitialise();
Your code does not work because it is not doing what you are expecting it to do. Switch blocks take in a value, and compare each case to the given value, looking for equality. Your comparison value is an integer, but most of your case expressions resolve to a boolean value.
So, for example, say liCount = 2. Your first case will not match, because 2 != 0. Your second case, (liCount<=5 && liCount>0) evaluates to true, but 2 != true, so this case will not match either.
For this reason, as many others have said, you should use a series of if...then...else if blocks to do this.
Notice that we don't pass score to the switch but true. The value we give to the switch is used as the basis to compare against.
The below example shows how we can add conditions in the case: without any if statements.
function getGrade(score) {
let grade;
// Write your code here
switch(true) {
case score >= 0 && score <= 5:
grade = 'F';
break;
case score > 5 && score <= 10:
grade = 'E';
break;
case score > 10 && score <= 15:
grade = 'D';
break;
case score > 15 && score <= 20:
grade = 'C';
break;
case score > 20 && score <= 25:
grade = 'B';
break;
case score > 25 && score <= 30:
grade = 'A';
break;
}
return grade;
}
If you want pass any value in switch statement
and then apply condition on that passing value and
evaluate statement then you have to write switch
statement under an function and pass parameter in that
function and then pass true in switch expression like the
below example.
function numberChecker(num){
let age;
switch(true){
case num >= 0 && num <= 10:
age = "Child";
break;
case num >= 10 && num <= 20:
age = "Teenager";
break;
case num >= 20 && num <= 30:
age = "Young";
break;
default:
age = "Undefined!! Enter Age Between 0 - 30";
break;
}
console.log("WOW You Are " + age);
}
numberChecker(15);
Although in the particular example of the OP's question, switch is not appropriate, there is an example where switch is still appropriate/beneficial, but other evaluation expressions are also required. This can be achieved by using the default clause for the expressions:
switch (foo) {
case 'bar':
// do something
break;
case 'foo':
// do something
break;
... // other plain comparison cases
default:
if (foo.length > 16) {
// something specific
} else if (foo.length < 2) {
// maybe error
} else {
// default action for everything else
}
}

Categories

Resources