Javascript looping error with arrays - javascript

I am trying to prompt the user for a weight smaller than 126. Then my javascript is supposed to classify the weight into a category. I have used arrays but every time I loop it writes the 3rd array, superfly class. What can I do to make it function properly?
var wArray = ["fly", "superfly", "bantam", "superbantam", "feather"];
var weight = parseInt(prompt("What is your weight?"), 10);
while (weight > 126) {
alert('Please enter a weight lighter than 126');
weight = parseInt(prompt("What is your weight?"), 10);
}
recruit();
function recruit() {
var weightClass = wArray[0];
if (0 < weight && weight < 112) {
weightClass = wArray[1];
} else if (112 < weight && weight < 115) {
weightClass = wArray[2];
} else if (weight > 115 && weight < 118) {
weightClass = wArray[3];
} else if (weight > 118 && weight < 122) {
weightClass = wArray[4];
} else if (weight > 122 && weight < 126) {
weightClass = wArray[5];
}
document.getElementById("weight").innerHTML = ('You are in ' + weightClass + ' class!');
}

Your first if condition is incorrect. You say if (112 < weight < 115). This first does 112 < weight, then takes the result of that and compares it to 115.
112 < weight evaluates to true or false; when used in numeric comparisons, true is 1 and false is 0. (Obviously) both 1 and 0 will always be less than 115, so this condition will always be true.
Also note that this script should be run onload of the page. This is because the div with the ID weight may not have loaded when the script executes and attempts to populate it. You can do this by saying:
<script type="text/javascript">
var wArray = ["fly", "superfly", "bantam", "superbantam", "feather"];
function calculateWeight() {
var weight = parseInt(prompt("What is your weight?"), 10);
while (weight > 126) {
alert('Please enter a weight lighter than 126');
weight = parseInt(prompt("What is your weight?"), 10);
}
recruit();
}
function recruit() {
var weightClass = wArray[0];
if (weight >= 112 && weight < 115) {
weightClass = wArray[1];
} else if (weight >= 115 && weight < 118) {
weightClass = wArray[2];
} else if (weight >= 118 && weight < 122) {
weightClass = wArray[3];
} else if (weight >= 122 && weight < 126) {
weightClass = wArray[4];
}
document.getElementById("weight").innerHTML = ('You are in ' + weightClass + ' class!');
}
</script>
<body onload="calculateWeight()">
<!-- include body contents here -->
</body>

the line:
if (112 < weight < 115) {
Should be
if (112 < weight && weight < 115) {

Related

My code keeps returning undefined underneath the output

My JavaScript function keeps returning undefined underneath the correct output value.
let grade;
function getGrade(score) {
// Write your code here
if (score >= 25 && score <= 30) {
console.log('A');
}
else if (score >= 20 && score <= 25) {
console.log('B');
}
else if (score >= 15 && score <= 20) {
console.log('C');
}
else if (score >= 10 && score <= 15) {
console.log('D');
}
else if (score >= 5 && score <= 10) {
console.log('E');
}
else {
console.log('F');
}
return grade;
}
You haven't defined your grade. And it will always be undefined.
One way to do it is as follows:
function getGrade(score) {
var grade = "";
// Write your code here
if (score >= 25 && score <= 30) {
grade = "A";
}
else if (score >= 20 && score <= 25) {
grade = "B";
}
else if (score >= 15 && score <= 20) {
grade = "C";
}
else if (score >= 10 && score <= 15) {
grade = "D";
}
else if (score >= 5 && score <= 10) {
grade = "E";
}
else {
grade = "F";
}
return grade;
}
console.log(getGrade(27))
It seems you have return grade; at the bottom, but grade doesn't seem to be defined anywhere.
You should to set your variable "grade" value, or just delete
return grade;
Always check the console. It's currently singing at you, telling you grade is undefined.
You're trying to return something you haven't assigned a value to.
function getGrade(score) {
// ... //
return grade; //<-- nowhere do you define grade
}
Should be
function getGrade(score) {
let grade;
if (score >= 25 && score <= 30) grade = 'A';
else if (score >= 20 && score <= 25) grade = 'B';
else if (score >= 15 && score <= 20) grade = 'C';
else if (score >= 10 && score <= 15) grade = 'D';
else if (score >= 5 && score <= 10) grade = 'E';
else grade = 'F';
console.log(grade);
return grade;
}
Use return instead of console.log()
function getGrade(score) {
if (score >= 25 && score <= 30) {
return 'A'
}
else if (score >= 20 && score <= 25) {
return 'B'
}
else if (score >= 15 && score <= 20) {
return 'C';
}
else if (score >= 10 && score <= 15) {
return 'D';
}
else if (score >= 5 && score <= 10) {
return 'E';
}
else {
return 'F';
}
}
console.log(getGrade(20))
As there is difference of 5 b/w each grade range so you can use division and Math.floor
function getGrade(score) {
let grades = 'FEDCBA'
return score === 30 ? 'A' : grades[Math.floor((score)/5)]
}
console.log(getGrade(20))
console.log(getGrade(19))
console.log(getGrade(30))

Run multiple else if statements

When I run this code, only the INVALID (over 100) and High Distinction works. Any number below 80 also shows High Distinction. What have I done wrong?
function calculateGrade() {
var fvalue = Number(prompt('Please enter final score for unit. Enter a whole number only'));
document.write('The final score entered is ' + fvalue + '<br />');
if (fvalue > 100) {
document.write('INVALID');
} else if (80 <= fvalue <= 100) {
document.write('High Distinction');
} else if (70 <= fvalue <= 79) {
document.write('Distinction');
} else if (60 <= fvalue <= 69) {
document.write('Credit');
} else if (50 <= fvalue <= 59) {
document.write('Pass');
} else if (0 <= fvalue <= 49) {
document.write('Fail');
} else if (fvalue < 0) {
document.write('INVALID');
}
}
calculateGrade()
Your comparison syntax is invalid. You need to check one boundary at a time:
if (80 <= fvalue && fvalue <= 100) {
Same for the others.
To take it a step further, you only need to check one boundary, because the higher end is excluded by the else:
if (fvalue > 100) {
document.write('INVALID');
} else if (80 <= fvalue) {
document.write('High Distinction');
} else if (70 <= fvalue) {
// ...
This isn't java.
But you can surely try this.
else if ( (fvalue >= 80) && (fvalue<= 100)) {
document.write('High Distinction');

How to display error message when using a grade calculator in JavaScript?

Below is a grade calculator that will attach a letter grade to the number entered, using if/else statements. I am having trouble finding a way to display an error message if an out of ranger number or non numeric value is entered. Any suggestions? Thanks!
var entry;
var letterGrade;
entry = prompt("Enter number grade from 0 through 100\n" +
"Or enter 999 to end entries", 999);
entry = parseInt(entry);
if (entry <= 59)
letterGrade = "F";
else if (entry >= 60 && entry <= 69)
letterGrade = "D";
else if (entry >= 70 && entry <= 79)
letterGrade = "C";
else if (entry >= 80 && entry <= 89)
letterGrade = "B";
else if (entry >= 90 && entry <= 100)
letterGrade = "A";
alert("Number grade = " + entry + "\n" +
"Letter grade = " + letterGrade);
Well your out of range would be anything >100 so you can cover that with an else in the end:
[..]
else if (entry >= 90 && entry <= 100)
letterGrade = "A";
else
alert("Error, your number " + entry + " was out of range (>100)");
As for it not being a number, you can use isNaN():
if(isNaN(entry)){
alert("That was not a number!");
else {
if (entry <= 59)
letterGrade = "F";
....
}
Edit: I see your input is >0<101 so to catch negative numbers you would need to add this to your first if statement:
if (entry >= 0 && entry <= 59)
Add a check in the beginning to see if entry is a valid input:
if(isNaN(entry) || entry < 0 || entry > 100)
alert('Only a grade between 0 and 100 is allowed');
var entry
, letterGrade;
entry = parseInt(prompt("Enter number grade from 0 through 100\n" +
"Or enter 999 to end entries", 999));
if(isNaN(entry) || entry < 0)
alert('Only a grade between 0 and 100 is allowed');
else if (entry <= 59)
letterGrade = "F";
else if (entry >= 60 && entry <= 69)
letterGrade = "D";
else if (entry >= 70 && entry <= 79)
letterGrade = "C";
else if (entry >= 80 && entry <= 89)
letterGrade = "B";
else if (entry >= 90 && entry <= 100)
letterGrade = "A";
alert("Number grade = " + entry + "\n" +
"Letter grade = " + letterGrade);

Which style of code is better: being efficient or separating concerns?

I wonder if this might come down to personal taste or if there is a generally agreed upon answer to this. I've got a piece of code that could be written in one of two ways and though I think it's something of a trivial example in terms of efficiency, I'd like to know what the generally accepted answer is for future extrapolations.
Here's the code I currently have, essentially a score is passed and some text is updated accordingly. The colour of the text is also changed by the score value.
function getBSTotalText(score) {
var scoreText;
if (score >= 0 && score <= 12) {
scoreText = "0 - 12 HIGH RISK";
}
else if (score >= 13 && score <= 14) {
scoreText = "13 - 14 MODERATE RISK";
}
else if (score >= 15 && score <= 16) {
scoreText = "15 - 16 LOW RISK";
}
else if (score >= 16) {
scoreText = "16+ NO RISK";
}
else {
scoreText = "";
}
return scoreText;
}
function getBSTotalColour(score) {
var colour;
if (score >= 0 && score <= 12) {
colour = "red";
}
else if (score >= 13 && score <= 14) {
colour = "amber";
}
else if (score >= 15 && score <= 16) {
colour = "yellow";
}
else if (score >= 16) {
colour = "grey";
}
else {
colour = "white";
}
return colour;
}
Now I could easily refactor this into one function and just get it to return an array or object to save basically copying and pasting the same code into a distinct function which from my understanding would conform to DRY but then break SOLID. Would best practice be to keep these functions distinct or merge them into one?
In this example, I'd say there's a compelling reason to refactor to a single function as both functions are concerned with the same thing - getting some formatted text.
function getBSTotalDisplayInfo(score) {
var result = {};
if (score >= 0 && score <= 12) {
result.colour = "red";
result.scoreText = "0 - 12 HIGH RISK";
}
else if (score >= 13 && score <= 14) {
result.colour = "amber";
result.scoreText = "13 - 14 MODERATE RISK";
}
else if (score >= 15 && score <= 16) {
result.colour = "yellow";
result.scoreText = "15 - 16 LOW RISK";
}
else if (score >= 16) {
result.colour = "grey";
result.scoreText = "16+ NO RISK";
}
else {
result.colour = "white";
result.scoreText = "";
}
return result;
}
Check what part of the code is repeated and move that into an extra function. In your case it's actually quite easy:
function getBSTotal(score) {
// returns some kind of enum
if (score >= 0 && score <= 12)
return 0;
else if (score >= 13 && score <= 14)
return 1;
else if (score >= 15 && score <= 16)
return 2;
else if (score >= 16)
return 4;
else
return 5;
}
function getBSTotalText(score) {
// now map the enum either to a text
return ["0 - 12 HIGH RISK",
"13 - 14 MODERATE RISK",
"15 - 16 LOW RISK",
"16+ NO RISK"
][getBSTotal(score)] || "";
}
function getBSTotalColour(score) {
// … or map it to a color
return ["red",
"amber"
"yellow",
"grey",
"white"
][getBSTotal(score)];
}
You still can make it more efficient by evaluating getBSTotal(score) only once and passing that to the mapping functions instead of score.

Error in JavaScript return code?

Here is the javascript code:
There is an error in code where nightSurcharges is added to total cost even if pickUptime is less than 20.
function TaxiFare() {
var baseFare = 2;
var costPerMile = 0.50;
var nightSurcharge = 0.50; // 8pm to 6am, every night //its flat 0.50 and not per mile
var milesTravelled = Number(document.getElementById("miles").value) || 0;
if ((milesTravelled < 1) || (milesTravelled > 200)) {
alert("You must enter 1 - 200 miles");
document.getElementById("miles").focus();
return false;
}
var pickupTime = Number(document.getElementById("putime").value) || 0;
if ((pickupTime == "") || (pickupTime < 0) || (pickupTime > 23)) {
alert("The time must be 0-23 hours");
document.getElementById("putime").focus();
return false;
}
var cost = baseFare + (costPerMile * milesTravelled);
// add the nightSurcharge to the cost if it is after
// 8pm or before 6am
if (pickupTime >= 20 || pickupTime < 6) {
cost += nightSurcharge;
}
alert("Your taxi fare is $" + cost.toFixed(2));
}
I want nightSurcharge to be added only when pickupTime is >=20, but that's not working right now.
Any help is appreciated. Thanks
This seems obvious to me.
if (pickupTime >= 20 || pickupTime < 6) {
cost += nightSurcharge;
}
This code right here adds nightSurcharge to the cost if pickupTime is greater than or equal to 20, OR less than 6. So of course it's added if it's less than 6.
if (pickupTime >= 20) {
cost += nightSurcharge;
}
Now it will only add to it if it's greater or equal to 20.
your code is:
if (pickupTime >= 20 || pickupTime < 6)
so if pickupTime is less then 6 it'll enter the if as well
http://jsfiddle.net/7rdzC/

Categories

Resources