Switch case failing, returns NaN [duplicate] - javascript

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.

Related

Different results between if statement and Switch in Javascript [duplicate]

This question already has answers here:
JavaScript switch with logical operators?
(5 answers)
Closed 2 years ago.
I'm running two seemingly identical statements to check whether a number is positive, negative or zero.
The if statement returns the expected result.
The switch statement always returns the default.
Why?
In this example I pass "2" (type: number) and I get + in the if statement and ? in the switch statement.
// Verify whether a number is positive, negative or Zero:
function myFuncIf(y) {
let result = null;
console.log("y is " + y);
console.log("y is " + typeof(y));
if (y > 0) {
return "+";
} else if (y < 0) {
return "-";
} else {
return "?";
}
}
function myFuncSwitch(y) {
let result = null;
console.log("y is " + y);
console.log("y is " + typeof(y));
switch (y) {
case (y > 0):
result = "+";
break;
case (y < 0):
result = "-";
break;
default:
result = "?";
}
return result;
}
console.log(myFuncIf(2));
console.log(myFuncSwitch(2));
switch matches the value.
The value of y is 2.
Your first case will match True.
Your second will match False.
You probably want your switch to look like this:
switch (Math.sign(y)) {
case (1):
result = "+";
break;
case (-1):
result = "-";
break;
default:
result = "?";
}
See docs here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign

Best way to validate long list of random postal codes

I have a long list of postal codes I have to validate.
Link to postal codes
As you can see it's quite random there is no real order.
I tried making a switch and put in everything by hand like so:
switch (true) {
case ($(this).val().length < 5) :
console.log("not filled out");
break;
case (number >= 1001 && number <= 6999):
validated = true;
error = false;
break;
case (number >= 8001 && number <= 34999):
validated = true;
error = false;
break;
case (number >= 36001 && number <= 37999):
validated = true;
error = false;
break;
default:
console.log("error");
error = true;
}
But I quickly realised this would be a stupid long code.
What would be a better way to validate all the ranges of postal codes?
You can reduce your switch for something like this
switch (true) {
case ($(this).val().length < 5) :
console.log("not filled out");
break;
case (number >= 1001 && number <= 6999):
case (number >= 8001 && number <= 34999):
case (number >= 36001 && number <= 37999):
validated = true;
error = false;
break;
default:
console.log("error");
error = true;
}
You can then add the list of rules you need

javascript fizzbuzz switch statement

I'm currently taking the code academy course on Javascript and I'm stuck on the FizzBuzz task. I need to count from 1-20 and if the number is divisible by 3 print fizz, by 5 print buzz, by both print fizzbuzz, else just print the number. I was able to do it with if/ else if statements, but I wanted to try it with switch statements, and cannot get it. My console just logs the default and prints 1-20. Any suggestions?
for (var x = 0; x<=20; x++){
switch(x){
case x%3==0:
console.log("Fizz");
break;
case x%5===0:
console.log("Buzz");
break;
case x%5===0 && x%3==0:
console.log("FizzBuzz");
break;
default:
console.log(x);
break;
};
};
Switch matches the x in switch(x){ to the result of evaluating the case expressions. since all your cases will result in true /false there is no match and hence default is executed always.
now using switch for your problem is not recommended because in case of too many expressions there may be multiple true outputs thus giving us unexpected results. But if you are hell bent on it :
for (var x = 0; x <= 20; x++) {
switch (true) {
case (x % 5 === 0 && x % 3 === 0):
console.log("FizzBuzz");
break;
case x % 3 === 0:
console.log("Fizz");
break;
case x % 5 === 0:
console.log("Buzz");
break;
default:
console.log(x);
break;
}
}
I thought switch too,but no need.
for (var n = 1; n <= 100; n++) {
var output = "";
if (n % 3 == 0)
output = "Fizz";
if (n % 5 == 0)
output += "Buzz";
console.log(output || n);
}
Switch statement checks if the situation given in the cases matches the switch expression. What your code does is to compare whether x divided by 3 or 5 is equal to x which is always false and therefore the default is always executed. If you really want to use a switch statement here is one way you can do.
for (var i=1; i<=30; i++){
switch(0){
case (i % 15):
console.log("fizzbuzz");
break;
case (i % 3):
console.log("fizz");
break;
case (i % 5):
console.log("buzz");
break;
default:
console.log(i);
}
}
Not to too my own horn but this is much cleaner:
var numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
for (var i = 1; i <= numbers.length; i++) {
if (i % 15 === 0) {
console.log("FizzBuzz");
} else if (i % 5 === 0) {
console.log("Buzz");
} else if (i % 3 === 0) {
console.log("Fizz");
} else {
console.log(i);
}
};
The switch(true) part of this statement helped me. I was trying to do a switch statement for fizzbuzz. My solution incorporates the coding style of Rosettacodes - general solution. Most significantly the use of force typing to shorten the primary conditionals. I thought, it was valuable enough to post:
var fizzBuzzSwitch = function() {
for (var i =0; i < 101; i++){
switch(true) {
case ( !(i % 3) && !(i % 5) ):
console.log('FizzBuzz');
break;
case ( !(i % 3) ):
console.log('Fizz');
break;
case ( !(i % 5) ):
console.log('Buzz');
break;
default:
console.log(i);
}
}
}
Here's what made it clear for me, might help :
It's a misinterpretation of what switch (x){} means.
It doesn't mean : "whenever whatever I put inbetween those brackets is true, when the value of x changes."
It means : "whenever x EQUALS what I put between those brackets"
So, in our case, x NEVER equals x%3===0 or any of the other cases, that doesn't even mean anything. x just equals x all the time. That's why the machine just ignores the instruction. You are not redefining x with the switch function. And what you put inbetween the brackets describes x and x only, not anything related to x.
In short :
With if/else you can describe any condition.
With switch you can only describe the different values taken by the variable x.
Here's a solution incorporating #CarLuvr88's answer and a switch on 0:
let fizzBuzz = function(min, max){
for(let i = min; i <= max; i++){
switch(0){
case i % 15 : console.log('FizzBuzz'); break;
case i % 3 : console.log('Fizz'); break;
case i % 5 : console.log('Buzz'); break;
default : console.log(i); break;
}
}
}
fizzBuzz(1,20)
We can use a function to find a multiple of any number and declare two variables to identify these multiples so that if you want to change the multiples you only need to change at max 2 lines of code
function isMultiple(num, mod) {
return num % mod === 0;
}
let a = 3;
let b = 5;
for(i=0;i<=100;i++){
switch(true){
case isMultiple(i,a) && isMultiple(i,b):
console.log("FizzBuzz")
case isMultiple(i,a):
console.log("Fizz");
case isMultiple(i,b):
console.log("Buzz");
default:
console.log(i);
}
}

Switch statement for a range not working

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.

Find the sum of a Javascript array and divide by its length

I'm almost embarrassed to ask this.
I'm a beginner programmer, and Javascript is very confusing to me. I managed to put together this much with the help of my instructor, but there are some simple things I can't get right.
I tried search Stack Overflow for a thread that would answer my question, but all of them I've seen contain code that I haven't learned about yet, so they're all just gibberish to me.
What I'm trying to do is add all the values of an Array and divide the sum by the array's length, ergo, find the average. The description of the assignment is find the average of any number of students' grades.
My two problems are
I can't figure out how to get the sum of all numeric values in the Array and,
For some reason, array.length returns one more than the actual length of the Array, even if I add a -1. (ex. if I enter 6 values, the array.length would return 7.)
I know where the problem is but I can't figure out what I need to enter. This assignment is due tomorrow, so anyone's time and effort is appreciated.
Here is my script:
<script type="text/javascript">
var allGrades = new Array();
var g = 0;
var l = 0;
var s = 0;
var t = 0;
do {
allGrades[g] = window.prompt("Please enter one grade for each window. After you enter a grade, enter an 'x' to see the average of the grades you entered.", "")
g++;
}
while (allGrades[g - 1] != "x")
for (l = 0; l < allGrades.length - 1; l++) {
s += allGrades[l] // Where I think the problem is
}
t == s / g - 1;
g == allGrades.length - 1; //
window.alert(g)
switch (t) {
case (t >= 90):
window.alert("Your average grade is " + (t) + ". " + "This is an A.")
break;
case (t >= 80 && t < 90):
window.alert("Your average grade is " + (t) + ". " + "This is a B.")
break;
case (t >= 70 && t < 80):
window.alert("Your average grade is " + (t) + ". " + "This is a C.")
break;
case (t >= 60 && t < 70):
window.alert("Your average grade is " + (t) + ". " + "This is a D.")
break;
case (t <= 60):
window.alert("Your average grade is " + (t) + ". " + "This is a failing grade.")
break;
}
</script>
I'm sorry if what I'm asking seems dumb. I've only been taking web programming for about two months, so I could really use some help!
Kyle
== is the comparison operator. You need to use the assignment operator (=) here:
t==s/g-1;
And the lines near it.
Also, for your own sake, do not use single-letter variable names unless you have a good reason for doing so.
Here's a cleaner way of writing the script:
var grades = [];
do {
var input = window.prompt("Please enter one grade for each window. After you enter a grade, enter an 'x' to see the average of the grades you entered.", "");
grades.push(parseFloat(input));
} while (input != 'x');
var sum = 0;
for (int i = 0; i < grades.length; i++) {
sum += grades[l];
}
var average = (sum / grades.length) * 100;
var grade;
if (average >= 90) {
grade = 'A';
} else if (average >= 80) {
grade = 'B';
} else if (average >= 70) {
grade = 'C';
} else if (average >= 60) {
grade = 'D';
} else {
grade = 'failing grade';
}
alert('Your average grade is ' + average + '. ' + 'This is a ' + grade);
t==s/g-1;
g==allGrades.length-1; //
Are both Comparisons, for assignment they should be
t=s/g-1;
g=allGrades.length-1;

Categories

Resources