Switch statement for a range not working - javascript

I am using a switch case in javascript to find a range, but its not working. Have I done something wrong?
function mapPriceRange(value){
var range = '';
switch(value)
{
case (value >= 0 && value <= 25):
range = '0_25';
break;
case (value >= 25 && value <= 40):
range = '25_40';
break;
case (value >= 40 && value <= 60):
range = '40_60';
break;
case (value >= 60 && value <= 100):
range = '60_100';
break;
case (value >= 100 && value <= 150):
range = '100_150';
break;
case (value >= 150 && value <= 200):
range = '150_200';
break;
case (value >= 200 && value <= 300):
range = '200_300';
break;
case (value >= 300 && value <= 500):
range = '300_500';
break;
case (value >= 500 && value <= 1000):
range = '500_1000';
}
return range;
}
console.log(mapPriceRange(500));
I am always getting an empty string.

Just replace switch(value) to switch(true) and it should work. See jsFiddle.

use below code
function checkRange(x, n, m) {
if (x >= n && x <= m) { return x; }
else { return !x; }
}
var x = 5;
function mapPriceRange(value){
var range = '';
switch(value)
{
case checkRange(x, 0, 25):
range = '0_25';
break;
case checkRange(x, 25, 40):
range = '25_40';
break;
case checkRange(x, 40, 60):
range = '40_60';
break;
case checkRange(x, 60, 100):
range = '60_100';
break;
case checkRange(x, 100, 150):
range = '100_150';
break;
case checkRange(x, 150, 200):
range = '150_200';
break;
case checkRange(x, 200, 300):
range = '200_300';
break;
case checkRange(x, 300, 500):
range = '300_500';
break;
case checkRange(x, 500, 1000):
range = '500_1000';
}
return range;
}
console.log(mapPriceRange(500));

Switch cases in Javascript only with strings. They coerce any input they receive in either the switch or in the case to string before comparing it. Hence, your value.toString() is getting compared to the "true" and "false" strings in the various cases, which is returning false in every case.
Using an ifElse ladder is the best way around it and refer to any of the other answers for a possible workaround which relies on returning either value.toString() or switch over "true" instead of value.

Related

How can i write these if statements as a single nested switch

I am trying to write this if statement here as a switch statement
if (value < 2500) {
paystackFees = value * 0.015;
};
if (paystackFees > 2000) {
paystackFees = 2000
};
Well, there is no hard rule whether to use a switch or if-else but I'd prefer to use a switch whenever I’m switching on the value of a single variable having at least two options with constant values to differentiate between. Anyways You can use a switch by simply putting a switch(true) and having your conditions placed as it is.
if (value < 2500) {
paystackFees = value * 0.015;
if (paystackFees > 2000) {
paystackFees = 2000
};
};
With switch:
switch(true) {
case value < 2500:
paystackFees = value * 0.015;
break;
case value < 1500:
// If you wish to extend it further
paystackFees = value * 0.015;
break;
default:
// Have a default value here
break;
}
switch(true){
case payStackFees > 2000:
payStackFees = 2000;
break
case payStackFees > 3500 && payStackFees < 4000
payStackFees = 3800;
break;
default:
break;
}
You can write a switch statement as follows:
switch(true){
case value < 2500:
paystackFees = value * 0.015;
break;
case paystackFees > 2000:
paystackFees = 2000
break;
default:
break;
}
But it seems a bit problematic as a value can meet both requirements, e.g:
2250 < 2500 && 2250 > 2000
So the order of your switch cases will determine the ending value of paystackFees. You can also omit break statements, in that case your result will entirely depend on the very last case.

Can a switch statement containing truthy values be written as an object literal lookup?

I have the following code displaying an image based on gamma values of the gyroscope. My first shot at it was to write a switch statement but having used object literals before I thought this could be a cleaner alternative. Is there any way to do this with the following code? Or any other cleaner solution?
switch (true) {
case (gamma <= -28):
view360.goToItem(0);
break;
case (gamma <= -24):
view360.goToItem(1);
break;
case (gamma <= -20):
view360.goToItem(2);
break;
case (gamma <= -16):
view360.goToItem(3);
break;
case (gamma <= -12):
view360.goToItem(4);
break;
case (gamma <= -8):
view360.goToItem(5);
break;
case (gamma <= -4):
view360.goToItem(6);
break;
case (gamma <= 0):
view360.goToItem(7);
break;
case (gamma <= 4):
view360.goToItem(8);
break;
case (gamma <= 8):
view360.goToItem(9);
break;
case (gamma <= 12):
view360.goToItem(10);
break;
case (gamma <= 16):
view360.goToItem(11);
break;
case (gamma <= 20):
view360.goToItem(12);
break;
case (gamma <= 24):
view360.goToItem(13);
break;
default:
view360.goToItem(13);
}
Your indexes are a function of the gamma, so you should write it as a function that captures that relationship. It looks like the relationship is simply (28 + gamma) / 4 with an additional check gamma is greater than 60. Since you are using inequalities to capture the in-between values, you need to divide by 31 and take the floor. This will allow both 3 and 4 to return 8 for example. So this should match your switches:
function getIndex(g) {
return g > 60 ? 13 : Math.floor((31 + g) / 4)
}
view360.goToItem(getIndex(gamma))
Not in this case, because you're using <= rather than =. Your whole method here would be better expressed with if and else - switch(true) is not really a switch.
Here's a switch you could convert to an object literal:
switch ( val ) {
case 'a': return 'hello';
case 'b': return 'goodbye';
}
Could be:
return { a: 'hello', b: 'goodbye' }[ val ];
Because the result of your switch (the argument to goToItem) is sequential (0, 1, 2...) you could use an array for this.
var gammaValues = [ -28, -24, -20, -16 /* etc */ ];
var idx = gammaValues.findIndex( value => gamma <= value );
if ( index !== -1 ) view360.goToItem( idx );
May be using map can help
const mapBreakpointToItem = {
-28: 0,
-24: 1,
...
};
Object.keys(mapBreakpointToItem).some((breakpoint) => {
if (gamma <= breakpoint) {
const item = mapBreakpointToItem[breakpoint];
view360.goToItem(item);
return true;
}
return false;
});
Or you can use math Math.floor((gamma + 31) / 4 for mapping breakpoints and items, but if something is changed its easier to change map object.

=> operator "undefined" error while trying to compare values in a switch statement

I'm taking an introductory course on Javascript at my college and in my assignment, I had to write a function that took a value passed into the parameter and compares it through a switch statement. This is what I did:
function grader(mark) {
switch (mark) {
case (mark >= 80 && mark <= 100) :
return 'A';
break;
case (mark >= 70 && mark <= 79) :
return 'B';
break;
case (mark >= 60 && mark <= 69) :
return 'C';
break;
case (mark >= 50 && mark <= 59) :
return 'D';
break;
case (mark >= 0 && mark <= 49) :
return 'F';
break;
}
}
But the error I'm getting on scratchpad is this:
Exception: SyntaxError: expected expression, got '>'
#Scratchpad/2:3
*/
/*
undefined
*/
What does it mean when an operand is undefined?
NO switch cases cannot check a value in the range.
switch (expression) {
case value1:
//Statements executed when the
//result of expression matches value1
[break;]
case value2:
//Statements executed when the
//result of expression matches value2
[break;]
That clearly tells that the case should be a specific value.
You should go with tradational if else if
if (mark >= 80 && mark <= 100){
return 'A';
}
else if (mark >= 70 && mark <= 79) {
return 'B';
}

Switch case for comparing values

I want to use switch case for the values.
How can i compare values in case like <= or >=
case<240:
It gives error...
thanks.
Yes, this should be possible.
Here's an example:
var x = 5;
switch (true) {
case (x < 240):
alert("Less than 240");
break;
case (x >= 240):
alert("Greater than or equal to 240");
break;
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
switch (true) {
case x < 240:
/* ... */
}
you have to compare with some value in this case and use space in between:
var x=100;
switch(true) {
case x < 100:
alert("Less than 100");
break;
case (x >= 100):
alert("greater or equal to 100");
break;
}

Using mathematics in a switch statement case? [duplicate]

Am I writing the correct switch case with conditions?
var cnt = $("#div1 p").length;
alert(cnt);
switch (cnt) {
case (cnt >= 10 && cnt <= 20):
alert('10');
break;
case (cnt >= 21 && cnt <= 30):
alert('21');
break;
case (cnt >= 31 && cnt <= 40):
alert('31');
break;
default:
alert('>41');
}
For some reason, the alert does not occur when the conditions are matched!
A switch works by comparing what is in switch() to every case.
switch (cnt) {
case 1: ....
case 2: ....
case 3: ....
}
works like:
if (cnt === 1) ...
if (cnt === 2) ...
if (cnt === 3) ...
Therefore, you can't have any logic in the case statements.
switch (cnt) {
case (cnt >= 10 && cnt <= 20): ...
}
works like
if (cnt === (cnt >= 10 && cnt <= 20)) ...
and that's just nonsense. :)
Use if () { } else if () { } else { } instead.
You should not use switch for this scenario. This is the proper approach:
var cnt = $("#div1 p").length;
alert(cnt);
if (cnt >= 10 && cnt <= 20)
{
alert('10');
}
else if (cnt >= 21 && cnt <= 30)
{
alert('21');
}
else if (cnt >= 31 && cnt <= 40)
{
alert('31');
}
else
{
alert('>41');
}
This should work with this :
var cnt = $("#div1 p").length;
switch (true) {
case (cnt >= 10 && cnt <= 20):
alert('10');
break;
case (cnt >= 21 && cnt <= 30):
alert('21');
break;
case (cnt >= 31 && cnt <= 40):
break;
default:
alert('>41');
}
Something I came upon while trying to work a spinner was to allow for flexibility within the script without the use of a ton of if statements.
Since this is a simpler solution than iterating through an array to check for a single instance of a class present it keeps the script cleaner. Any suggestions for cleaning the code further are welcome.
$('.next').click(function(){
var imageToSlide = $('#imageSprite'); // Get id of image
switch(true) {
case (imageToSlide.hasClass('pos1')):
imageToSlide.removeClass('pos1').addClass('pos2');
break;
case (imageToSlide.hasClass('pos2')):
imageToSlide.removeClass('pos2').addClass('pos3');
break;
case (imageToSlide.hasClass('pos3')):
imageToSlide.removeClass('pos3').addClass('pos4');
break;
case (imageToSlide.hasClass('pos4')):
imageToSlide.removeClass('pos4').addClass('pos1');
}
}); `
What you are doing is to look for (0) or (1) results.
(cnt >= 10 && cnt <= 20) returns either true or false.
--edit--
you can't use case with boolean (logic) experessions. The statement cnt >= 10 returns zero for false or one for true. Hence, it will we case(1) or case(0) which will never match to the length.
--edit--
function date_conversion(start_date){
var formattedDate = new Date(start_date);
var d = formattedDate.getDate();
var m = formattedDate.getMonth();
var month;
m += 1; // JavaScript months are 0-11
switch (m) {
case 1: {
month="Jan";
break;
}
case 2: {
month="Feb";
break;
}
case 3: {
month="Mar";
break;
}
case 4: {
month="Apr";
break;
}
case 5: {
month="May";
break;
}
case 6: {
month="Jun";
break;
}
case 7: {
month="Jul";
break;
}
case 8: {
month="Aug";
break;
}
case 9: {
month="Sep";
break;
}
case 10: {
month="Oct";
break;
}
case 11: {
month="Nov";
break;
}
case 12: {
month="Dec";
break;
}
}
var y = formattedDate.getFullYear();
var now_date=d + "-" + month + "-" + y;
return now_date;
}
Switch case is every help full instead of if else statement :
switch ($("[id*=btnSave]").val()) {
case 'Search':
saveFlight();
break;
case 'Update':
break;
case 'Delete':
break;
default:
break;
}
Ok it is late but in case you or someone else still want to you use a switch or simply have a better understanding of how the switch statement works.
What was wrong is that your switch expression should match in strict comparison one of your case expression. If there is no match it will look for a default. You can still use your expression in your case with the && operator that makes Short-circuit evaluation.
Ok you already know all that. For matching the strict comparison you should add at the end of all your case expression && cnt.
Like follow:
switch(mySwitchExpression)
case customEpression && mySwitchExpression: StatementList
.
.
.
default:StatementList
var cnt = $("#div1 p").length;
alert(cnt);
switch (cnt) {
case (cnt >= 10 && cnt <= 20 && cnt):
alert('10');
break;
case (cnt >= 21 && cnt <= 30 && cnt):
alert('21');
break;
case (cnt >= 31 && cnt <= 40 && cnt):
alert('31');
break;
default:
alert('>41');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div1">
<p> p1</p>
<p> p2</p>
<p> p3</p>
<p> p3</p>
<p> p4</p>
<p> p5</p>
<p> p6</p>
<p> p7</p>
<p> p8</p>
<p> p9</p>
<p> p10</p>
<p> p11</p>
<p> p12</p>
</div>

Categories

Resources