Different result of an if else on Javascript [duplicate] - javascript

This question already has answers here:
What's the prettiest way to compare one value against multiple values? [duplicate]
(8 answers)
Closed 1 year ago.
I don't know why I keep getting the console.log from if statement even both averages are above 100.
Where did I put my mistake?
const dolphinsScores = 97 + 112 + 101;
const dolphinsAverage = dolphinsScores / 3;
const koalasScores = 109 + 95 + 123;
const koalasAverage = koalasScores / 3;
console.log(dolphinsAverage);
console.log(koalasAverage);
if (dolphinsAverage || koalasAverage < 100) {
console.log('One of the team is already lost')
} else if (dolphinsAverage > koalasAverage) {
console.log('Team Dolphins are the winner of the competition! 🐬🎉');
} else if (koalasAverage > dolphinsAverage) {
console.log('Team Koalas are the winner of the competition! 🐨🎉');
}

this statement
if (dolphinsAverage || koalasAverage < 100)
resolve as
if (true || koalasAverage < 100)
what you need is
if (dolphinsAverage < 100 || koalasAverage < 100)

Your if condition was checking if there is any value in dolphinsAverage which will always be true if there is any value in dolphinsAverage. So try this if you want to know if dolphinsAverage's value is less than 100.
if (dolphinsAverage < 100 || koalasAverage < 100) {
console.log('One of the team is already lost')
} else if (dolphinsAverage > koalasAverage) {
console.log('Team Dolphins are the winner of the competition! 🐬🎉');
} else if (koalasAverage > dolphinsAverage) {
console.log('Team Koalas are the winner of the competition! 🐨🎉');
}

const dolphinsScores = 97 + 112 + 101;
const dolphinsAverage = dolphinsScores / 3;
const koalasScores = 109 + 95 + 123;
const koalasAverage = koalasScores / 3;
console.log(dolphinsAverage);
console.log(koalasAverage);
if ((dolphinsAverage < 100) || (koalasAverage < 100)) {
console.log('One of the team is already lost')
} else if (dolphinsAverage > koalasAverage) {
console.log('Team Dolphins are the winner of the competition! 🐬🎉');
} else if (koalasAverage > dolphinsAverage) {
console.log('Team Koalas are the winner of the competition! 🐨🎉');
}

your if statement should be
if (dolphinsAverage < 100 || koalasAverage < 100) {

Related

I want to check the grade of the students marks , based on average

What's wrong with this code? I tried get marks using array and pass the array in to function parameters and calculate the average in that function.
const marks = [100,100,80];
var summ = 0;
function calculateGrade(){
for(let i=0; i<=marks.length;i++){
summ = summ+marks[i];
var avg = (summ/marks.length);
}
if(avg<=59){
console.log('F');
}
else if(avg>=60 && avg<=69){
console.log('D');
}
else if(avg>=70 && avg<=79){
console.log('C');
}
else if(avg>=80 && avg<=89){
console.log('B');
}
else if(avg>=90 && avg<=100){
console.log('A');
}
}
console.log(calculateGrade(marks));
const sum = marks.reduce((partialSum, a) => partialSum + a, 0);
const marks = [100, 100, 80];
var summ = 0;
//issue one (Tmarks were missing )
function calculateGrade(Tmarks) {
// issues 2 ( <= should be < )
for (let i = 0; i < Tmarks.length; i++) {
summ += Tmarks[i];
}
var avg = summ / Tmarks.length;
if (avg <= 59) {
console.log("F");
} else if (avg >= 60 && avg <= 69) {
console.log("D");
} else if (avg >= 70 && avg <= 79) {
console.log("C");
} else if (avg >= 80 && avg <= 89) {
console.log("B");
} else if (avg >= 90 && avg <= 100) {
console.log("A");
}
}
console.log(calculateGrade(marks));
Following were the issues in your code
You were not getting the parameters in function definition
issues 2 ( <= should be < )
You just added an extra = in your for loop
i<=marks.length
instead of
i<marks.length
So while calculating the sum & average, a garbage value gets added up.
You are very close
const marks = [100, 100, 80];
function calculateGrade(marks) {
let summ = 0;
for (let i = 0; i < marks.length; i++) {
summ += marks[i];
}
const avg = summ / marks.length;
let grade = '';
if (avg < 59) {
grade = 'F';
} else if (avg <= 69) {
grade = 'D';
} else if (avg <= 79) {
grade = 'C';
} else if (avg <= 89) {
grade = 'B';
} else {
grade = 'A';
}
return grade;
}
console.log(calculateGrade(marks));
There are couple of mistakes in your code.
1.
for(let i=0; i<=marks.length;i++)
marks.length is 3. Array index starting from 0.
const marks = [100,100,80];
index 0 is 100.
index 1 is 100.
index 2 is 80.
When you add i<=marks.length, this is equals to i<=3.
= in here will run the loop extra circle and this will return NaN because there are only 3 elements in you array and array indexing is 0 based.
2.
for(let i=0; i<=marks.length;i++){
summ = summ+marks[i];
var avg = (summ/marks.length);
}
avg is out of scope. you have defined avg inside the loop and trying to access it outside of the loop. Anything declared in the loop is scoped to that loop and are not available outside the loop.
3.
console.log(calculateGrade(marks));
Your calculateGrade() function is not accepting any parameters. So you can't pass any parameter into this function.
4.
console.log(calculateGrade(marks));
since calculateGrade() function is not returning any value, this will print nothing. So you don't need to call this inside a console.log();.
I have simplified your code as below.
const marksArr = [100, 100, 80];
calculateGrade(marksArr);
function calculateGrade(marks) {
console.log('calling calculateGrade(marks)...');
var avg = (marksArr.reduce(function(a, b) {
return a + b;
}, 0)) / marksArr.length;
console.log('avg is', avg);
if (avg <= 59) {
console.log('Grade', 'F');
} else if (avg >= 60 && avg <= 69) {
console.log('Grade', 'D');
} else if (avg >= 70 && avg <= 79) {
console.log('Grade', 'C');
} else if (avg >= 80 && avg <= 89) {
console.log('Grade', 'B');
} else if (avg >= 90 && avg <= 100) {
console.log('Grade', 'A');
}
}
` calculateGrade(){
let marks = [100,100,80];
let summ = 0;
let avg = 0;
for(let i = 0; i < marks.length; i++){
summ = summ+marks[i];
avg = (summ/marks.length);
}
if(avg<=59){
console.log('F');
}
else if(avg>=60 && avg<=69){
console.log('D');
}
else if(avg>=70 && avg<=79){
console.log('C');
}
else if(avg>=80 && avg<=89){
console.log('B');
}
else if(avg>=90 && avg<=100){
console.log('A');
}
}`
> array start from 0

Conditional exercise addWithSurcharge

I can't figure why b arguments greater than 20 don't work here. See results
Exercise:
Write a function addWithSurcharge that adds two amounts with surcharge. For each amount less than or equal to 10, the surcharge is 1. For each amount greater than 10 and less than or equal to 20, the surcharge is 2. For each amount greater than 20, the surcharge is 3.
Example: addWithSurcharge(10, 30) should return 44.
function addWithSurcharge(a,b) {
let sur1 = 0
if (a <= 10) {
sur1 = 1;
} else if (10 < a <= 20) {
sur1 = 2;
} else if (a > 20) {
sur1 = 3;
}
let sur2 = 0
if (b <= 10) {
sur2 = 1;
} else if (10 < b <= 20) {
sur2 = 2;
} else if (b > 20) {
sur2 = 3;
}
return a + b + sur1 + sur2;
}
Issue
The reason is that you condition else if (10 < a <= 20) evaluates to true.
10 < a will be evaluated to true
true <= 20 will be evaluated to true.
So the number will evaluated as boolean and every number greater than 0 evaluates to true. That's the reason why true <= 20 evaluates to true
You can check this by this snippet
console.log(true <= 20)
console.log(true <= 0)
console.log(true <= -3)
Solution
To define a range you should use the && operator like this
else if (10 < b && b <= 20)
Then it will
check if 10 < 30 evaluate to true
check if 30 <= 20 evaluate to false
true && false will evaluate to false
function addWithSurcharge(a,b) {
let sur1 = 0
if (a <= 10) {
sur1 = 1;
} else if (10 < a && a <= 20) {
sur1 = 2;
} else if (a > 20) {
sur1 = 3;
}
let sur2 = 0
if (b <= 10) {
sur2 = 1;
} else if (10 < b && b <= 20) {
sur2 = 2;
} else if (b > 20) {
sur2 = 3;
}
return a + b + sur1 + sur2;
}
console.log(addWithSurcharge(10,30))

Problem with Javascript function not returning total sum in a for loop with if conditions

I am writing pure javascript without any HTML and I am having trouble with one of my functions that would need to return the total "course points."
The program consists of prompting the user the # of course taken followed by the grade received which is pushed in the "grades" array. The function calculateCP will allow it to reiterate every element of the array and is suppose to give me the total course points given the following if conditions.
Please help why my function isn't working! The output is returning only the first element of the array, not the total sum of all elements.
calculateCP = () => {
let coursePoints;
let total = 0;
for (let i = 0; i < grades.length; i++) {
if (grades[i] >= 90) {
coursePoints = 4;
} else if (grades[i] >= 80 && grades[i] < 90) {
coursePoints = 3;
} else if (grades[i] >= 70 && grades[i] < 80) {
coursePoints = 2;
} else if (grades[i] >= 60 && grades[i] < 70) {
coursePoints = 1;
} else if (grades[i] < 60) {
coursePoints = 0;
}
return total = total + coursePoints;
}
}
const grades = [];
let noOfCourses = parseInt(prompt("Please enter # of courses taken: "));
console.log("\n")
for (let i = 0; i < noOfCourses; i++) {
grades.push(prompt('Enter grade recieved '));
}
console.log(calculateCP());
}
In the for loop you just want to sum the values.. only once you're done, return the total :) something like this..
calculateCP = () => {
let coursePoints;
let total = 0;
for (let i = 0; i < grades.length; i++) {
if (grades[i] >= 90) {
coursePoints = 4;
} else if (grades[i] >= 80 && grades[i] < 90) {
coursePoints = 3;
} else if (grades[i] >= 70 && grades[i] < 80) {
coursePoints = 2;
} else if (grades[i] >= 60 && grades[i] < 70) {
coursePoints = 1;
} else if (grades[i] < 60) {
coursePoints = 0;
}
total = total + coursePoints;
}
return total;
}
const grades = [];
let noOfCourses = parseInt(prompt("Please enter # of courses taken: "));
console.log("\n")
for (let i = 0; i < noOfCourses; i++) {
grades.push(prompt('Enter grade recieved '));
}
console.log(calculateCP());
}
try to remove the return statement from the for loop and put it right after it..
change this:
return total = total + coursePoints;
to this:
... for loop
total = total + coursePoints;
}
return total;

Recursively setting a value depending on range using JavaScript

I don't know how to word this but this is what I'm trying to do:
if (score >= 0 && score <= 10) overallScore = 0;
else if (score >= 11 && score <= 20) overallScore = 1;
else if (score >= 21 && score <= 30) overallScore = 2;
else if (score >= 31 && score <= 40) overallScore = 3;
else if (score >= 91 && score <= 100) overallScore = 9;
...
Is there any way to recursively do this using a function?
overallScore = Math.max(0, Math.floor((score - 1) / 10));
no need for recursion. But if you need that:
const getOverall = score => score <= 10 ? 0 : getOverall(score - 10) + 1;
Recursion is not really appropriate here, since you can get the required value in constant time. Recursion becomes interesting when you need at least O(logn) time.
But as you ask for it, here is one way to make it recursive:
function range(score, depth = 0) {
return score <= 10 || depth >= 9 ? 0 : range(score-10, depth+1) + 1;
}
console.log(range(0)); // 0
console.log(range(10)); // 0
console.log(range(11)); // 1
console.log(range(60)); // 5
console.log(range(91)); // 9
console.log(range(110)); // 9

Codewars: Grasshopper - Grade book challenge

This is one of those times where the solution is staring me right in the face but I can't seem to find it! So please be patient with me. The kata instruction is the following:
Complete the function so that it finds the mean of the three scores passed to it and returns the letter value associated with that grade.
Numerical Score Letter Grade
90 <= score <= 100 'A'
80 <= score < 90 'B'
70 <= score < 80 'C'
60 <= score < 70 'D'
0 <= score < 60 'F'
Tested values are all between 0 and 100. There is no need to check for negative values or values greater than 100.
Here is my solution:
function getGrade (s1, s2, s3) {
var score = (s1 + s2 + s3) / 3;
if (90 <= score && score >= 100) {
return 'A';
} else if (80 <= score && score > 90) {
return 'B';
} else if (70 <= score && score > 80) {
return 'C';
} else if (60 <= score && score > 70) {
return 'D';
} else if (0 <= score && score > 60) {
return 'F';
}
}
getGrade(5,40,93);
getGrade(30,85,96);
getGrade(92,70,40);
Can't for the life of me figure out what I am doing wrong.
Your conditions in if statement are all wrong. These are the right conditions
function getGrade (s1, s2, s3) {
var score = (s1 + s2 + s3) / 3;
if (score >= 90 && score <= 100) {
return 'A';
} else if (score >= 80 && score < 90) {
return 'B';
} else if (score >= 70&& score < 80) {
return 'C';
} else if (score >= 60 && score < 70) {
return 'D';
} else {
return 'F';
}
}
your conditions are wrong and you don't need multiple check in same if .Change your code to this:
function getGrade (s1, s2, s3) {
var score = (s1 + s2 + s3) / 3;
if (score >= 90 && score <= 100) {
return 'A';
} else if (score >= 80 ) {
return 'B';
} else if (score >= 70 ) {
return 'C';
} else if (score >= 60) {
return 'D';
} else{
return 'F';
}
}
console.log(getGrade(5,40,93));
console.log(getGrade(30,85,96));
console.log(getGrade(92,70,40));
You could use only if clauses without else parts and check only the lower bound, because you have already checked the upper bound.
The check for upper 100 is missing, because your given range is between 0 and 100.
function getGrade(s1, s2, s3) {
var score = (s1 + s2 + s3) / 3;
if (score >= 90) {
return 'A';
}
if (score >= 80) {
return 'B';
}
if (score >= 70) {
return 'C';
}
if (score >= 60) {
return 'D';
}
return 'F';
}
console.log(getGrade(5, 40, 93));
console.log(getGrade(30, 85, 96));
console.log(getGrade(92, 70, 40));
Whenever you find yourself writing long chains of if-else statements, see if you can find a pattern and use a lookup table. Here, we have only 5 grade buckets, but what if we had 20 or 100? You can see the if-else approach isn't scalable.
In this case, if we use the string "FFFFFFDCBAA" then we've enumerated all 5 grade buckets in a way that lets us index into after dividing the score by 10. The code for that would be: "FFFFFFDCBAA"[score/10|0] where | 0 is the floor operation, chopping off the decimal. The extra "A" handles the case of 100.
Secondly, the arguments to the function (s1, s2, s3) make no sense. Why 3 scores? If we have 4 score, or 20 scores, the function can't be used and we have to rewrite the whole function with the right number of arguments (and the 20-argument one will be pretty ugly). I realize this header is what the kata author gave you, but there's no reason we can't make it handle any number of arguments using (...args) and still pass the tests. If we take the average of the arguments using args.reduce((a, e) => a + e, 0) / args.length, we're left with the following solution:
const sum = a => a.reduce((a, e) => a + e, 0);
const avg = a => sum(a) / a.length;
const getGrade = (...args) => "FFFFFFDCBAA"[avg(args)/10|0];
[
[0],
[0, 100, 50],
[90, 95, 100],
[80, 60],
[81, 79],
[80, 59],
].forEach(test => console.log(`${test} => ${getGrade(...test)}`));

Categories

Resources