Wierd execution of if condition - javascript

Else condition is executed every time. If input is '11' answer is 'f' not 'D', I know the last condition should be else if but according to the logic of input is 11 output should be 'D'
function getGrade(score) {
let grade;
var score1 = Number(score);
// Write your code here
if (score1 > 25 && score <= 30)
grade = "A";
else if (score1 > 20 && score <= 25)
grade = "B";
else if (score1 > 15 && score <= 20)
grade = "C";
else if (score1 > 10 && score <= 15)
grade = "D";
else if (score1 > 5 && score <= 10)
grade = "E";
else (score1 > 0 && score <= 5)
grade = "F";
return grade;
}

Is it a copy-paste? Then it's a matter of typo.
else (score1 > 0 && score <= 5)
grade = "F";
if is missing here. Therefore, (score1 > 0 && score <= 5) is interpreted as the thing to do (so, evaluate an expression), and the next line is outside of any else/if branch and simply gets executed always.

You can use the parenthesis around the else if. Also for the last condition you can simple use else instead of else if
function getGrade(score) {
let grade;
var score1 = Number(score);
console.log(score1)
// Write your code here
if (score1 > 25 && score <= 30) {
grade = "A";
} else if (score1 > 20 && score <= 25) {
grade = "B";
} else if (score1 > 15 && score <= 20) {
grade = "C";
} else if (score1 > 10 && score <= 15) {
grade = "D";
} else if (score1 > 5 && score <= 10) {
grade = "E";
} else {
grade = "F";
}
return grade;
}
console.log(getGrade(11))

A better approach, is to use an early exit paradigm, starting with wrong values and then take a ladder of conditions which rely on the conditions before.
function getGrade(score) {
var score1 = Number(score);
if (isNaN(score1) || score1 > 30 || score1 < 0) return;
if (score1 > 25) return "A";
if (score1 > 20) return "B";
if (score1 > 15) return "C";
if (score1 > 10) return "D";
if (score1 > 5) return "E";
return "F";
}

Related

I don't know how to fix my grade calculator function

I just have no idea what I did wrong to get undefined answers logged to my console.
I've tried deleting the && clauses but this didn't seem to help at all; actually it made it worse.
function gradeCalculator(grade) {
if (grade >= 90) {
console.log ("A");
} else if (grade >= 80 && grade <= 89) {
console.log ("B");
} else if (grade >= 70 && grade <= 79) {
console.log ("C");
} else if (grade >= 60 && grade <= 69) {
console.log ("D");
} else (grade <= 59)
console.log ("F");
}
console.log(gradeCalculator(92)); //=> "A"
console.log(gradeCalculator(84)); //=> "B"
console.log(gradeCalculator(70)); //=> "C"
console.log(gradeCalculator(61)); //=> "D"
console.log(gradeCalculator(43)); //=> "F"
I expected the output to log to the console as:
'A'
'B'
'C'
'D'
'F'
But it actually came out as:
'A'
'F'
undefined
'B'
'F'
undefined
'C'
'F'
undefined
'D'
'F'
undefined
'F'
undefined
I would really appreciate any and all help, thank you so much! =)
function gradeCalculator(grade) {
if (grade >= 90) {
console.log("A");
} else if (grade >= 80 && grade <= 89) {
console.log("B");
} else if (grade >= 70 && grade <= 79) {
console.log("C");
} else if (grade >= 60 && grade <= 69) {
console.log("D");
} else {
console.log("F");
}
}
gradeCalculator(92); //=> "A"
gradeCalculator(84); //=> "B"
gradeCalculator(70); //=> "C"
gradeCalculator(61); //=> "D"
gradeCalculator(43); //=> "F"
The problems were:
else (grade <= 59) - else doesn't take a condition, and this case wasn't wrapped in { and }
console.log(gradeCalculator(92)); //=> "A" - The function wasn't returning anything, so you were console.log'ing an undefined value (since the logging was in the function itself)
function gradeCalculator(grade) {
if (grade >= 90) {
console.log ("A");
} else if (grade >= 80 && grade <= 89) {
console.log ("B");
} else if (grade >= 70 && grade <= 79) {
console.log ("C");
} else if (grade >= 60 && grade <= 69) {
console.log ("D");
} else if(grade <= 59){
console.log ("F");
}
}
Your last else should be else if with a condition.
(You can just put else but else if with a condition is more maintainable.

Simple Grading system. Keep getting error 'undefined'. What I'm I doing wrong?

I keep getting the error 'undefined' but I only have one variable(grade) which I've already defined. Assistance will be highly appreciated.
//Grading system:
// A = 84 and above // D = 50 - 59
// B = 71 - 83 // E = 49 and below
// C = 60 - 70
function Grading_System(grade){
var grade;
switch(grade){
case(grade >= 84):
return "A";
break;
case(grade < 84 && grade > 70):
return "B";
break;
case(grade >= 60 && grade <= 70):
return "c";
break;
case(grade >= 50 && grade < 60):
return "D";
break;
case(grade < 50):
return "E";
break;
}
}
console.log(Grading_System(69));
You need to check with true, because the expression is evaluated and checked against the switch statement's value with a strict comparison.
switch (true) {
An you could omit the break statements, because the previous return statement ends the function.
function getGrade(grade) {
switch (true) {
case (grade >= 84):
return "A";
case (grade < 84 && grade > 70):
return "B";
case (grade >= 60 && grade <= 70):
return "c";
case (grade >= 50 && grade < 60):
return "D";
}
return "E";
}
console.log(getGrade(69));
You are re-declaring 'grade' inside of the function but not initialising it, so it will be undefined. Remove the line var grade; and see if it works. Also it is a good idea to include a default, so that if no switch matches, the default is given, and I don't think you need the 'break's if you are returning:
function Grading_System(grade){
var grade;
switch(grade){
case(grade >= 84):
return "A";
case(grade < 84 && grade > 70):
return "B";
case(grade >= 60 && grade <= 70):
return "c";
case(grade >= 50 && grade < 60):
return "D";
case(grade < 50):
return "E";
default:
return "F";
}
}

JavaScript Grading Scale Calculating error with multiple wrong answers?

I'm new to code so my mistake is probably obvious but,
When I go and test the calculator, it reads "A" then where ever the proper grade should be then Undefined. Idk where I'm going wrong.
I've tried a lot of different variations, and can't get the calculator to work properly. I'm not sure where the problem is.
function calculateGrade(grade) {if (parseInt >= "90"){
alert ("A");
}
else if (parseInt >= "80" === parseInt < "90"){
alert ("B");
}
else (parseInt >= "70" === parseInt < "80");{
alert ("C");
}
if (parseInt >= "60" === parseInt < "70"){
alert ("D");
}
else if (parseInt < "60"){
alert ("F");
}}
var inputGrade = prompt("Enter a grade:");
var parsedInt = parseInt(inputGrade);
var finalGrade = calculateGrade(parsedInt);
alert(finalGrade);
Suggestions and errors in your code
You already have parsed into number, so leave the '90' quotes from the numbers.
Don't use magic names and global variables. Your function accepts the grade argument. Use it in your code.
Your if else conditions are wrong. Some of them are without else if. You can left the second part of each else if conditions.
Return the final which you expect from the function.
function calculateGrade(grade) {
let final = '';
if (grade >= 90) {
final = 'A';
} else if (grade >= 80) {
final = 'B';
} else if (grade >= 70) {
final = 'C';
} else if (grade >= 60) {
final = 'D';
} else {
final = 'F';
}
return final;
}
let inputGrade = prompt("Enter a grade:");
let parsedInt = Number.parseInt(inputGrade);
let finalGrade = calculateGrade(parsedInt);
alert(finalGrade);
You could use a patttern with early exit and start frim the smallest value check to the greatest value.
The early exit returns a function and no more check is performed, because the function has ended with return statement.
For taking an integer value with parseInt, you should use a radix of 10, because without and with leading zero the number is treated as octal number, which you do not want.
A last advice, please do not use name of build in functions or objects or reserved words as variable names. This could lead to not proper working code and to searching without reason.
function calculateGrade(grade) {
if (grade < 50){
return "F";
}
if (grade < 60){
return "E";
}
if (grade < 70) {
return "D";
}
if (grade < 80) {
return "C";
}
if (grade < 90) {
return "B";
}
return "A";
}
var inputGrade = prompt("Enter a grade:"),
grade = parseInt(inputGrade, 10),
finalGrade = calculateGrade(grade);
console.log(finalGrade);
Try it
function calculateGrade(grade) {
if (grade < 60){
alert ("F");
}
else if (grade >= 60 && grade < 70){
alert ("D");
}
else if(grade >= 70 && grade < 80);{
alert ("C");
}
else if (grade >= 80 && grade < 90){
alert ("B");
}
else if (grade >= 90){
alert ("A");
}
}
var inputGrade = prompt("Enter a grade:");
var parsedInt = parseInt(inputGrade);
var finalGrade = calculateGrade(parsedInt);
alert(finalGrade);

JavaScript: Numerical Grade to Letter Grade

1. Create a function toLetterGrade that takes an array of percentages and returns an array of corresponding grade letters. For example:
toLetterGrade([90,80,55,85]); //returns ["A","A-","C","A"]
2. Create a function toGradePoints that takes an array of letter grades and returns a corresponding array of grades points. For example:
toGradePoints(["A","A-","C","A"]); //returns [4.0,3.7,2.0,4.0]
3. Create a function GPA that takes an array of percentages and returns the corresponding grade point average.
I'm trying to do number 1, and this is the code I have so far, but it only gives me the letter grade for the last number in the array. What am I doing wrong?
var arr
function toLetterGrade(arr) {
for (i = 0; i < arr.length; i++) {
if (arr[i] >= 85) {
textG = "A";
} else if (arr[i] >= 80) {
textG = "A-";
} else if (arr[i] >= 75) {
textG = "B+";
} else if (arr[i] >= 70) {
textG = "B";
} else if (arr[i] >= 65) {
textG = "B-";
} else if (arr[i] >= 60) {
textG = "C+";
} else if (arr[i] >= 55) {
textG = "C";
} else if (arr[i] >= 50) {
textG = "D";
} else {
textG = "F";
}
}
return textG;
}
document.write(toLetterGrade([90, 80, 70]))
Output is B.
You are overwriting your variable with every cycle of the loop, that's why you are getting only one - the last grade.
I suggest you to use an empty array variable to store results inside.
With every loop you will assign new grade to the textG variable and then push it into the result array. The textG variable gets reseted with every loop textG = '' so there's no risk to duplicate/overwrite results.
After all cycles of the for loop, the result array is returned.
function toLetterGrade(arr) {
var textG = '';
var result = [];
for (i = 0; i < arr.length; i++) {
textG = '';
if (arr[i] >= 85) {
textG = "A";
} else if (arr[i] >= 80) {
textG = "A-";
} else if (arr[i] >= 75) {
textG = "B+";
} else if (arr[i] >= 70) {
textG = "B";
} else if (arr[i] >= 65) {
textG = "B-";
} else if (arr[i] >= 60) {
textG = "C+";
} else if (arr[i] >= 55) {
textG = "C";
} else if (arr[i] >= 50) {
textG = "D";
} else {
textG = "F";
}
result.push(textG);
}
return result;
}
document.write(toLetterGrade([90, 80, 70]))
For the first part, you could use an object and iterate the keys for the wanted grade.
function getGrade(p) {
var grade = 'F';
Object.keys(grades).some(function (k) {
if (p >= grades[k]) {
grade = k;
return true;
}
});
return grade
}
var grades = { A: 85, 'A-': 80, B: 70, 'B-': 65, 'C+': 60, C: 55, D: 50, F: '' }
console.log([90, 80, 55, 85].map(getGrade));
.as-console-wrapper { max-height: 100% !important; top: 0; }
You're assigning the grade to a variable and then overwriting it with each iteration.
try textG.push('A') instead
You are overwriting your return value with each iteration.
Try creating an array, and adding the solution onto the array.
var solutionArr = [];
solutionArr.push("A");
jsfiddle
I make this simple code to check letter grade from a numerical
const letterGrade = (n) => {
let resultGrade = "";
if (n >= 90) {
resultGrade = "A";
} else if (n >= 80 || n > 89) {
resultGrade = "B";
} else if (n >= 70 || n > 79) {
resultGrade = "C";
} else if (n >= 60 || n > 69) {
resultGrade = "D";
} else if (n < 59) {
resultGrade = "E";
} else {
alert("Input your grade first");
}
return `Your grade is ${resultGrade}`;
};
console.log(letterGrade(75));

Why won't this javascript hot/cold app run?

added a while loop, and trying to end the loop by entering finish inside the loop. The game is still running after it the game is completed.
var number = Math.floor(Math.random() * 100) + 1; // generate random #
var guess;
var guessCount = 0;
var correctGuess = false;
var diff;
var correct = false;
while (!correct) {
correct = guessFunction();
var finish = false;
}
function guessFunction(){
guess = prompt('I am thinking of a number between 1 and 100. What is it?');
guessCount += 1;
var guessInt = parseInt(guess); //turn guesses into interger
if (guess == number){ //which number is bigger, guess or number
alert('Correct!' + 'That was a total of ' + guessCount + ' guesses.');
correctGuess = true;
finish = true;
}
else if (guessInt > number) {
diff = guessInt - number;
}
else if (guessInt < number) {
diff = number - guessInt;
}
if (diff >= 1 && diff <= 10 && !correctGuess) {
alert('Very Hot');
guessFunction();
}
else if (diff < 10 && diff <= 20 && !correctGuess){
alert('Hot');
guessFunction();
}
else if (diff < 20 && diff <= 30 && !correctGuess){
alert('Warm');
guessFunction();
}
else if (diff < 30 && diff <= 50 && !correctGuess){
alert('Cold');
guessFunction();
}
else if (diff > 50 && !correctGuess){
alert('Ice Cold');
guessFunction();
}
}
guessFunction();
Trying to get this code to run but it only allows for 2 alert windows when guessing the random number. Im not sure how to get this to run, perhaps the guessFunction is not running?
var number = Math.floor(Math.random() * 100) + 1; // generate random #
var guess;
var guessCount = 0;
var correctGuess = false;
var diff;
function guessFunction(){
guess = prompt('I am thinking of a number between 1 and 100. What is it?');
guessCount += 1;
var guessInt = parseInt(guess); //turn guesses into interger
if (guess == number){ //which number is bigger, guess or number
alert('Correct!');
}
else if (guessInt > number) {
diff = guessInt - number;
}
else if (guessInt < number) {
diff = number - guessInt;
}
}
guessFunction();
if (diff >= 1 && diff <= 10) {
alert('Very Hot');
guessFunction();
}
else if (diff < 10 && diff <= 20){
alert('Hot');
guessFunction();
}
else if (diff < 20 && diff <= 30){
alert('Warm');
guessFunction();
}
else if (diff < 30 && diff <= 50){
alert('Cold');
guessFunction();
}
else if ( diff > 50){
alert('Ice Cold');
guessFunction();
}
The script stops executing because you only call your function twice. If you want this to run until the user guesses the right number, you probably want a while loop:
var correct = false;
while (!correct) {
// guessFunction could return true if they get it right
correct = guessFunction();
}
Yes, your script is only executing twice before exiting. You've got your nesting wrong:
var number = Math.floor(Math.random() * 100) + 1; // generate random #
var guess;
var guessCount = 0;
var correctGuess = false;
var diff;
function guessFunction(){
guess = prompt('I am thinking of a number between 1 and 100. What is it?');
guessCount += 1;
var guessInt = parseInt(guess); //turn guesses into interger
if (guess == number){ //which number is bigger, guess or number
alert('Correct!');
correctGuess = true;
}
else if (guessInt > number) {
diff = guessInt - number;
}
else if (guessInt < number) {
diff = number - guessInt;
}
if (diff >= 1 && diff <= 10 && !correctGuess) {
alert('Very Hot');
guessFunction();
}
else if (diff < 10 && diff <= 20 && !correctGuess){
alert('Hot');
guessFunction();
}
else if (diff < 20 && diff <= 30 && !correctGuess){
alert('Warm');
guessFunction();
}
else if (diff < 30 && diff <= 50 && !correctGuess){
alert('Cold');
guessFunction();
}
else if (diff > 50 && !correctGuess){
alert('Ice Cold');
guessFunction();
}
}
guessFunction();
EDIT:
My answer is more verbose than it needs to be so that it relates directly to your question. The next step for you is to implement the better solution of a while loop mentioned in Menello's answer in your script.

Categories