Switch is not properly working in javascript - javascript

I have a switch statement which has several cases. These cases compare values and assign a text to a variable. But when I try to execute this switch, it always executes the default case. But my condition is true.. Why?
Here is my value
Apartment
Here is my code
var rental_cat = $('#rentals_type').val();
alert(rental_cat);
var rental_type = "";
switch (rental_cat) {
case (rental_cat == "Apartment"):
rental_type='daily';
alert(rental_type);
break;
case (rental_cat == "Office"):
rental_type='work_daily';
alert(rental_type);
break;
default:
rental_type='other';
alert(rental_type);
break;
}
When I execute this switch, it always gives me "other"

Remove the conditional expression inside the "case" clause.
Try this:
var rental_cat = $('#rentals_type').val();
alert(rental_cat);
var rental_type = "";
switch (rental_cat) {
case "Apartment":
rental_type='daily';
alert(rental_type);
break;
case "Office":
rental_type='work_daily';
alert(rental_type);
break;
default:
rental_type='other';
alert(rental_type);
break;
}

switch (rental_cat) {
case (rental_cat == "Apartment"):
is equivalent to
switch (rental_cat) {
case true:
which in turn is equivalent to
if (rental_cat === true)
You don't put a condition in the case, the condition is created as an equality check between the switch and the cases, so it should be like this instead:
switch (rental_cat) {
case "Apartment":

a switch is not the right structure to deal with this problem. Here I'd recommend a map:
var rentalTypesByCat = {
DEFAULT: "other",
"Apartement": "daily",
"Office": "work_daily",
}
var rental_cat = $('#rentals_type').val();
console.log("rental_cat:", rental_cat);
var rental_type = rentalTypesByCat[rental_cat] || rentalTypesByCat.DEFAULT;
console.log("rental_type:", rental_type);
or if you need it a bit more explicit (for example because some of your mapped values may be falsy themselves):
var rental_type = rentalTypesByCat[rental_cat in rentalTypesByCat? rental_cat: "DEFAULT"];
console.log("rental_type:", rental_type);

Related

Using different array's with switch statements

I am creating a recycling app and am attempting to use a switch statement to provide the user with instructions on what to do with the item upon entering into an input field. I'm a little turned around on how to call it (I am very new to switch). Eventually I want to have a few different arrays according to material. How would I place the item's within an array in the a switch? Would I be better off with if else statements? Any advice would be much appreciated!
const plasticItem = ["Milk Jug , Shampoo, Deodarant, Soda Bottle"];
function recycleItem(plasticItem) {
let instructions = "";
switch (true) {
case plasticItem:
instructions = "Put in recycling";
break;
}
}
I made this code which should work:
function recycleItem(){
const x = document.querySelector("input").value;
switch(x) {
case "Milk Jug":
console.log("Milk");
break;
case "Shampoo":
// code block
console.log("Shampoo");
break;
case "Deodarant":
console.log("Deodarant");
break
case "Soda Bottle":
console.log("Soda Bottle");
break
default:
// code block
}
}

Switch statement only returns the default case

Can someone help me understand, why is my switch case returning the default value. Even when I change all values it only returns the default at first I thought it was a hoisting issue in my code but after debugging it's I found it's the statement, it ignores all other cases. (p.s please don't be mean I just want to understand, the other examples I've seen aren't simply explained and don't have much up votes so I did try.)
var shippingMethod = document.querySelector("[name=r_method]:checked").value;
var shippingChoice;
switch(shippingMethod) {
case "usps":
shippingChoice = 2;
break;
case "ups":
shippingChoice = 3;
break;
default:
shippingChoice = 0;
break;
}
console.log(shippingChoice);
I would suggest adding an if statement to verify there is a value for shippingMethod. As well, when querying for the value, make sure to include quote ("") around the value of the name.
var shippingMethod = "default";
var shippingChoice;
if (document.querySelector('[name="r_method"]:checked') != null)
{
shippingMethod = document.querySelector('[name="r_method"]:checked').value;
}
switch(shippingMethod) {
case "usps":
shippingChoice = 2;
break;
case "ups":
shippingChoice = 3;
break;
default:
shippingChoice = 0;
break;
}
console.log(shippingChoice);

Creating a unit conversion method for the number prototype

I am currently trying to create a unit conversion for metric and English scale as a method for the number prototype. Heres my code:
Number.prototype.UnitConversion = function (units){
switch (units){
case "Metric":
this = this/100;
return this;
case "English":
this = this/12;
return this;
}
}
var a = 5;
alert(a.UnitConversion("Metric"))
However I get a left side invalid argument error. Why is that?
this is immutable in JavaScript, meaning you cannot reassign it, see: this SO post. However, you could simply return the value of some calculation done on it:
Number.prototype.UnitConversion = function(units) {
switch (units){
case "Metric":
return this/100;
case "English":
return this/12;
default:
return;
}
}
var a = 5;
console.log(a.UnitConversion("Metric"))
Its because an unexpected assignment to this. Maybe try a more readable, clean solution? Something like this:
Number.prototype.UnitConversion = function (units){
let conversion;
switch (units){
case "Metric":
conversion = this/100;
break;
case "English":
conversion = this/12;
break;
//always add a default case
}
return conversion;
}

switch nested inside while loop to allow user to play again-Javascript

The purpose of the code is to allow users to play the game as many times as they want. I keep on getting stuck in infinite loop and I am not sure why. P.s. I need to stick to switch statements.
var color1 = prompt('Pick a color');
while (true){
switch (color1) {
case (color1 = 'blue'):
document.write("nope");
break;
case (color1 = 'yellow'):
document.write("nope");
break;
case (color1 = 'white'):
document.write("nope");
break;
case (color1 = 'gray'):
document.write("nope");
break;
case (color1 = 'green'):
document.write("yes");
break;
case (color1 = 'pink'):
document.write("nope");
break;
case(color1 = 'purple'):
document.write("nope");
break;
case (color1 = 'orange'):
document.write("nope");
break;
case (color1 = 'green'):
document.write("nope");
break;
case (color1 = 'magenta'):
document.write("nope");
break;
case (color1 = 'red'):
document.write("nope");
break;
}
if(color1 = false)
alert('Thanks')
}
There are several problems in your code:
The = operator does assignment, you need === or == for comparison.
You are not using case correctly within your switch: you need to just put the value you want to match against color1, don't try to do a comparison as if it were an if condition. So you need something like:
switch (color1) {
case 'red':
document.write("nope");
break;
It doesn't make sense to list a whole bunch of different incorrect colours in different cases, because even aside from the fact that the user might enter values not in your list, really the logic should be "Is it green?" yes/no. An if statement would make much more sense than a switch, but since you've said you have to use switch then you should have one case for the correct answer and then use default to catch all other values:
switch (color1) {
case 'green':
document.write("yes");
break;
default:
document.write("nope");
break;
}
Or in a hypothetical case where you legitimately needed to list several values but have them do the same thing you should make use of a "fall through" like this:
switch (color1) {
case 'blue':
case 'yellow':
case 'white':
document.write("nope");
break;
case 'green':
document.write("yes");
break;
}
The final if needs to break out of the while loop when the condition is true - currently all it does is show an alert, hence the infinite loop.
Testing if (color1 === false) (after fixing the operator) doesn't make sense, because color1 won't ever be false: if the user clicks the Cancel button on the prompt() then the value will be null, so test for that. You could also test for an empty string. Except you can move that logic into a case instead of having an if after the switch statement. Instead of while(true), use while(!finished) and add a finished variable that you set to true when the user clicks the Cancel button.
The prompt() needs to be inside the loop, otherwise the user will only be prompted once before the loop starts and the loop will keep repeating testing the same value over and over.
Using document.write() isn't a good plan, but I'm declaring that issue out of scope for this question. In the meantime, you should at least output <p> elements or something so that each "nope" and "yes" appears on its own line.
Putting that all together:
var finished = false;
while (!finished) {
var color1 = prompt('Pick a color');
switch (color1) {
case null:
case '':
alert('Thanks');
finished = true;
break;
case 'green':
document.write("<p>yes</p>");
break;
default:
document.write("<p>nope</p>");
break;
}
}

Switch Case Regex Test

var path = location.pathname;
switch(path){
case (/\/memberlist/).test(path) :getCSS('url-22.css'); break;
case (/\/register/).test(path): getCSS('url-6.css'); break;
case (/buy-credits/g).test(path): getCSS('url-7.css'); break;
case (/\/?u(\d+)friends$/).test(path): getCSS('url-8.css'); break;
case (/\/privmsg/).test(path): getCSS('url-9.css'); break;
case (/\/?u(\d+)wall$/).test(path): getCSS('url-4.css'); break;
}
function getCSS(url,media){
var a = document.createElement('link');
a.href=url;
a.media= media || 'screen';
a.rel="stylesheet";
return (document.getElementsByTagName('head')[0].appendChild(a));
}
That is my code, and for some reason it's not running the function that should run. For testing purpose we could change var path="/memberlist" and it still won't run. Can someone explain to me why this won't run. Don't really use switch statements
change
switch(path){
to
switch(true){
as you can see in thread I'm reffering to in comment.
None of the answers posted show a correct method to use a RegExp pattern in a switch case so I thought I'd post:
switch (myVar) {
case 'case1':
/...do work
break
case /[a-z]*/.test(myVar) && myVar:
/...regex match, do work
break
}
switch-case doesn't work that way.
regex.test() method returns a boolean (true/false) and you are comparing that against the input string itself which will not be true for any of the case statement.
You need to convert switch-case into multiple if / else if / else block to execute your logic.
Just for the record, the switch case could be rewritten to:
getCSS(
/\/memberlist/).test(path) && 'url-22.css' ||
/\/register/).test(path) && 'url-6.css' ||
/buy-credits/g).test(path) && 'url-7.css' ||
/\/?u(\d+)friends$/) && 'url-8.css' ||
/\/privmsg/).test(path) && 'url-9.css' ||
/\/?u(\d+)wall$/).test(path) && 'url-4.css' ||
'default'
);
Or rewrite getCSS, using a helper object
var path2url = {
css: [
{re: /\/register/, css: 'url-22.css'},
{re: /buy-credits/g, css: 'url-6.css'},
{re: /\/?u(\d+)friends$/, css: 'url-8.css'},
{re: /\/privmsg/, css: 'url-8.css'},
{re: /\/?u(\d+)wall$/, css: 'url-4.css'}
],
getURL: function(path) {
var i = this.css.length;
while (--i) {
if (this.css[i].re.test(path)) {
return this.css[i].css;
}
}
return null; // or something default
}
};
function getCSS(path,media){
var a = document.createElement('link');
a.href= path2url.getURL(path); // <=
a.media= media || 'screen';
a.rel="stylesheet";
return (document.getElementsByTagName('head')[0].appendChild(a));
}
Have a look
switch(str){
case (/(abc|xyz)/.test(str) ? str : false):
// Do some stuff
break;
default:
// Do default stuff
}

Categories