Home > Back-end >  Why is my code returning the else statement and undefined and not the totalBasketballScore?
Why is my code returning the else statement and undefined and not the totalBasketballScore?

Time:09-20

I really thought I had this code correct. I am trying to calculate basketball score with free throws, 2 pointers and 3 pointers. The output when I console.log the totalBasketballScore ends up being 'All entries must be numbers' and undefined. What do I need to change so I get the score when I put the 3 values in the parameters?

function totalBasketballScore(numberFreeThrows, numberMidRange, numberThreePointers) {
  const freeThrows = 1;
  const midRange = 2;
  const threePointers = 3;

  if (typeof numberFreeThrows === 'number' && numberMidRange === 'number' && numberThreePointers === 'number') {
    let totalFreeThrows = freeThrows * numberFreeThrows;
    let totalMidRange = midRange * numberMidRange;
    let totalThreePointers = threePointers * numberThreePointers;
    let gameTotal = totalFreeThrows   totalMidRange   totalThreePointers;
    return gameTotal;

  } else {
    console.log('All Entries Must Be a Number');
  }
}
console.log(totalBasketballScore(1, 2, 4));

CodePudding user response:

You should use typeof per each parameter, like this:

if(typeof numberFreeThrows === 'number' && typeof numberMidRange === 'number' && typeof numberThreePointers === 'number'){

} else {

}

CodePudding user response:

Another approach that can be used is isNaN(). isNaN can be used to check if the value is Not a Number. If isNaN() returns false, the value is a number.

function totalBasketballScore(numberFreeThrows, numberMidRange, numberThreePointers) {
const freeThrows = 1;
  const midRange = 2;
  const threePointers = 3;

  if(isNaN(numberFreeThrows)=== false && isNaN(numberMidRange)=== false && isNaN(numberThreePointers)=== false) {
    let totalFreeThrows = freeThrows * numberFreeThrows;
    let totalMidRange = midRange * numberMidRange;
    let totalThreePointers = threePointers * numberThreePointers;
    let gameTotal = totalFreeThrows   totalMidRange   totalThreePointers;
    return gameTotal;

  } else {
    console.log('All Entries Must Be a Number');
  }
}
console.log(totalBasketballScore(1, 2, 4));
  • Related