How can i write this code block without conditions?

Would love to see explanations too.

(:slight_smile:

If you would return the letterGrader, you have to use conditional like that or switch, or if you like to more have flexibility to get score or the letter, you could refactor the code with something like this

let letterScore = function(totalScore){
  //switch or if statement
  return letterScore;
}

let gradScore = function(score, total=100, letter=false){
   let totalScore= (score* 100) / total;
   return letter ? this.letterScore(totalScore) : totalScore;
}
1 Like

Yeah, I don’t think it is possible without using at least one condition, but even with just one condition as I did below, that condition would be evaluated several times in the loop, I wouldn’t recommend it as your way is much clearer, besides the below would depend on a uniform grade scale like your original problem has, but if the scale is not uniformly distributed it won’t work.

const gradScore = (sScore, totalScore = 100) =>{
  let finalGrade = 'F';
  ['A', 'B', 'C', 'D', 'F'].forEach((grade, idx)=>{
    const gradeScale = (totalScore - (idx+1)*10)
    if(finalGrade === 'F' && sScore >= gradeScale) finalGrade = grade
  })
  return `You got ${finalGrade} (${(sScore *100) / totalScore}%)`
}
1 Like

As per requested… 0 conditions.

const gradScore = ((sScore, totalScore = 100) => {
  
    const score = Math.floor(sScore / 10);

    var grade = {
        10: 'A',
        9:  'A',
        8:  'B',
        7:  'C',
        6:  'D',
        5:  'F',
        4:  'F',
        3:  'F',
        2:  'F',
        1:  'F',
        0:  'F'
    }[score];

    return `You got ${grade} (${sScore}%)`;
});

let studantScore = gradScore(92);
console.log(studantScore);
1 Like

You can move the conditions somewhere else so that they aren’t in that particular code block and pretend they’re not there, but at the end of the day you have to have conditions somewhere, whether you do that via if/else, switch, or a table lookup

1 Like

Thanks! Its very interesting, can you explain to me that part [score] after the object? I didnt fully understand how this code block work.

Sure… it’s rather easy.

const cars = { 
     0: "BMW",
     1: "PORCHE"
};

If I did
console.log(cars[0]);

i would get BMW.

So all im doing is moving the [0] to the end of the object.

const cars = { 
     0: "BMW",
     1: "PORCHE"
}[0];

Which is also BMW. Then finally I’m changing the 0 to a variable.

let myVar = 0;
const cars = { 
     0: "BMW",
     1: "PORCHE"
}[myVar];

So now whenever I do:
console.log(cars) it really is executing console.log(cars[myVar]);

Wow… Thank you very much. It does make a lot of sense.