Can a mathematical operator be used in a switch expression? - javascript

I'm having a problem using a mathematical operator in a switch expression.
This is what my code currently looks like:
var x = 18;
var y = 82;
var result = x + y;
switch(result) {
case "200":
document.write("200!");
break;
case "500":
document.write("500!");
break;
case "100":
document.write("100! :)");
break;
default:
document.write("Something's not right..");
}
Explained: the variable "result" has a value of 100. I am trying to use that value with the switch operator, but it just isn't working.
I've also tried using the equation itself as the switch expression, but that doesn't work either.
P.S: I just started out with JavaScript. Bet I missed something obvious...

Change "100" to 100 and it works. switch must be using the semantics of === which means 'type and value are equal' vs ==, which will try to make the types similar and then compare.
EDIT -- here is a screenshot showing it working

You're comparing the number 100 to the string "100", that isn't the same. Try this:
var x = 18;
var y = 82;
var result = x + y;
switch(result) {
case 200:
document.write("200!");
break;
case 500:
document.write("500!");
break;
case 100:
document.write("100! :)");
break;
default:
document.write("Something's not right..");
}

You are using strings in your case statements. Take the quotes (") out and you should be fine.

Related

trying to use switch with if else statement to make operations. but but syntax error appears?

i am a javascript beginner , tried to make a program to insert two inputs of numbers and insert an operator to make a mathematical function and make an alert if the input is not correct. i don't know why a syntax error appears after case + and doesn't work .is there other way to make the program?
any suggetions?
thanks in advance
There are a few different issues with your code and I'll go over them one by one:
First, note that typeof for first_number and second_number will be number regardless of the input. You want to check for NaN instead using the isNaN function.
Second, you will want to wrap the cases of the switch statement in curly braces.
Third, the case values themselves should be in quotes in this case.
Fourth, you will want the break keyword after each of your cases to prevent them from falling through to the next case. There are valid use cases for that (such as multiple cases with the same block) but it's not what you want in this basic example.
All in all, your code should look like this, basically:
var first_number = parseInt(prompt("Please enter a number"));
var second_number = parseInt(prompt("Please enter a number"));
if (isNaN(first_number) || isNaN(second_number))
{
alert("Please enter valid numbers.");
}
var operator = prompt("Please enter an operator");
var result;
switch(operator)
{
case "+":
result = first_number + second_number;
break;
case "-":
result = first_number - second_number;
break;
case "*":
result = first_number * second_number;
break;
case "/":
result = first_number / second_number;
break;
default:
result = "Invalid operator.";
break;
}
alert(result);
Lastly, please post your actual code in the contents of the post in future instead of an image.

Switch case match with string

function getFieldType(value){
var type = "";
switch(value){
case "TEXT_BOX":
type=FieldTypeEnum.TEXT_BOX;
break;
case "PASSWORD":
type=FieldTypeEnum.PASSWORD;
break;
case "CHECK_BOX":
type=FieldTypeEnum.CHECK_BOX;
break;
case "RADIO_BUTTON":
type=FieldTypeEnum.RADIO_BUTTON;
break;
case "DROP_DOWN":
type=FieldTypeEnum.DROP_DOWN;
break;
case "SEARCH_CARD_BOX":
type=FieldTypeEnum.SEARCH_CARD_BOX;
break;
case "STATE_DROP_DOWN":
type=FieldTypeEnum.STATE_DROP_DOWN;
break;
case "ID_DROP_DOWN":
type=FieldTypeEnum.ID_DROP_DOWN;
break;
case "GENDER_DROP_DOWN":
type = FieldTypeEnum.GENDER_DROP_DOWN;
break;
default:
type = "";
}
return type;
}
I want to combined three drop down box (STATE_DROP_DOWN, ID_DROP_DOWN, GENDER_DROP_DOWN)into one .
Means I want something like below :
case String.endwith("_DROP_DOWN"):
type=FieldTypeEnum.ID_DROP_DOWN;
break;
Is it possible in JavaScript? If yes then how?
It is possible, in a javascript switch/case statement you can compare for string equality (which evaluates to true or false) or more complex statements which just as when testing for string equality, also evaluate to true or false (e.g. String.endwith("_DROP_DOWN")). However personally I would prefer the following:
STATE_DROP_DOWN:
// intentional fall through
ID_DROP_DOWN:
// intentional fall through
GENDER_DROP_DOWN:
//.. do your stuff
break;
I believe this way it is more clearly through which switch case you are falling in a certain situation.
You can put a ternary operator in the case, and test if it ends with "DROP_DOWN" return value otherwise blank string.
switch(value){
case value.endsWith("_DROP_DOWN") ? value : '' {
type=FieldTypeEnum.ID_DROP_DOWN;
break;
}
}

Switch statement with numeric values

Trying simple switch with random number.
It does not seem to work. Always getting to default case.
var x = 0;
x = (Math.random() * 10 + 1);
switch(x) {
case x >= 5:
console.log("the number is bigger than 5");
break;
case x <= 5:
console.log("the number is smaller than 5");
break;
default:
console.log("strange number");
}
console.log(x);
The output is always similar to that:
strange number
5.922413225153608
That's just not how switch statements work in JavaScript,1 what you're looking for there is an if/else if/else series instead:
if (x >= 5) {
console.log("the number is bigger than 5");
} else if (x <= 5) {
console.log("the number is smaller than 5");
} else {
console.log("strange number");
}
Two notes, though:
Your first and second cases both include 5; the first will win.
The only value for x that will reach the final else is NaN (or something that converts to NaN when converted to number), because NaN >= 5 and NaN <= 5 are both false.
In a comment you've said:
Thanks, the point is to practice switch.
If so, you'll either have to do the thing below (which probably isn't what your instructor wanted), or limit the range of values, because the cases of a switch are tested for exact match.
For instance, if you changed your code only allow integers, you could use cases with fall-through:
var x = 0;
x = Math.floor(Math.random() * 10 + 1); // Note change: Only integers
switch(x) {
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
console.log("the number is bigger than 5");
break;
case 1:
case 2:
case 3:
case 4:
console.log("the number is smaller than 5");
break;
default:
console.log("strange number");
}
console.log(x);
That makes use of the fact that cases fall through to the following case when you don't use break.
But you can't do that with your original x, because there are just too many floating-point values in the range 1 <= x < 11 to list.
JavaScript's switch does have a feature that makes it possible to use switch here, but an if/else if/else is almost certainly a better choice. Purely for completeness:
// PROBABLY NOT A GOOD IDEA
switch (true) {
case x >= 5:
console.log("the number is bigger than 5");
break;
case x <= 5:
console.log("the number is smaller than 5");
break;
default:
console.log("strange number");
break;
}
That works because unlike many languages, JavaScript's switch cases are allowed to be expressions, and they're tested in the order in which they appear in the switch (other than default, of course), with the first matching case being used.
But again, probably not great to use in the real world except in very, very limited situations.
Between case and : you have to have a value.
x >= 5 and x <= 5 are going to give you true or false, which x will then be compared to. Since x will always be a number, it will never be true or false so you will always hit the default.
Use if/else if/else instead.
You can't do in thatway. You have to do
switch(true) {
case x >= 5:
console.log("the number is bigger than 5");
break;
case x <= 5:
console.log("the number is smaller than 5");
break;
default:
console.log("strange number");
}
While switch is using strict comparison and you have already in the case clause already a comparison, you could change your switch statement to
switch(true) {
and use the rest, you have.

Switch combining cases string regex and number

Is there a way to create multiple cases in a single Javascript switch statement?
In my code I receive the value of a field via jQuery.
Is it possible that one case checks for string regex and another for number of the same variable?
I am thinking along the lines of:
var field = $(this).val();
var msg;
switch (field)
{
case field.test('Yes'):
msg = "FOO\n";
break;
case 10:
msg = "BAR\n";
break;
}
Although I saw here: Switch statement for string matching in JavaScript
That the way to use switch on strings is by sending the switch statement a "true" value.
What would be the most concise (and correct!) way to achieve this?
OK, compiling both answers above my code that worked and was most elegant IMO is:
var fieldVal = $(this).val();
var msg;
switch (true)
{
case /Yes/.test(fieldVal):
msg = "FOO";
break;
case fieldVal > 10 :
msg = "BAR";
break;
}
this works as separate if statements since we are evaluating whether or not the case returns true but in a clearer and more concise way that could give us the option to add totally disparate test statements in one switch.
the reason it works is probably that the case expression evaluated is interpreted as a true or false value and then checked against the main -
switch(true)
You can't the case need to single value, that's compared to switch expression, but you can put multiple cases to execute the same code:
switch (field) {
case 'Yes':
case 'yes':
case 'YES':
msg = "FOO\n";
break;
case 10:
msg = "BAR\n";
break;
}
but in order to use test as case you can pass true to switch (I found that trick in some open source project):
switch (true) {
case field.test('Yes'):
msg = "FOO\n";
break;
case field == 10:
msg = "BAR\n";
break;
}
but this is the same as if/else
Note: you're using test() incorrectly, it's a method of a regex object, so you need /Yes/.test(field) rather than field.test('Yes'). Anyway...
If you've only got two cases as shown then I'd use an if/else/else if structure:
var field = $(this).val();
var msg;
if(/Yes/.test(field)) {
msg = "FOO\n";
} else if (field === 10) {
msg = "BAR\n";
}
If you need to add additional cases I'd just add extra if else {} branches on the end.
If you have several specific numeric cases you might consider putting them in a switch with the regex tests in a default at the end:
switch (field) {
case 10:
msg = "BAR\n";
break;
case 30:
msg = "whatever\n";
break;
case 50:
msg = "hi\n";
break;
default:
if (/Yes/.test(field)) {
msg = "FOO\n";
else if (/No|N|False|/i.test(field)) {
msg = "blah\n";
}
break;
}
The switch (true) option you alluded to in the question is really just a messier version of an if/else/else if, so it doesn't really make sense unless you have some fall-through cases:
switch(true)
case /Yes/.test(field):
case /Y/.text(field):
case /Whatever/.text(field):
msg = "FOO\n";
break;
case field == 10:
msg = "BAR\n";
break;
}
...and even then an if with multiple conditions joined by || arguably just as tidy with appropriate newlines, and combining multiple regexes into a single one is probably a lot neater.

Replace with the regular expression

What regular expression I need to use to correct
if (text.indexOf("+") != -1) {
action = "+";
} else if (text.indexOf("-") != -1) {
action = "-";
} else if (text.indexOf("*") != -1) {
action = "*";
} else if (text.indexOf("/") != -1) {
action = "/";
}
this code
?
EDIT:
and how can I improve this code:
switch (action) {
case "+":
result = parseInt(array[0]) + parseInt(array[1]);
break;
case "-":
result = parseInt(array[0]) - parseInt(array[1]);
break;
case "*":
result = parseInt(array[0]) * parseInt(array[1]);
break;
case "/":
result = parseInt(array[0]) / parseInt(array[1]);
break;
default:
break;
}
Sorry for dull questions I am new in js.
You can use either of these:
var action = text.replace(/.*([+*/-]).*/,'$1');
var match = /[*+/-]/.exec(text);
var action = match && match[0];
If there's the possibility of newlines in your text then change the first to:
var action = text.replace(/[\d\D]*([+*/-])[\d\D]*/,'$1');
Edit: You can improve your switch statement by using, e.g.
// allow floating point values, and also
// don't accidentally interpret "011" as octal
array[0]*1 + array[1]*1;
For more details on why parseInt is probably bad, see this answer.
You can also remove the superfluous default section of your case statement. However, I suspect that your desired "improvement" was making fewer lines. Given that =-*/ are operators in JavaScript (and not methods), I cannot think of any way to avoid having four calculations (i.e. a switch or if/else if).
Whereas in Ruby you could, for example, use array[0].send(action,array[1]) to cover all four cases ;)

Categories

Resources