0

My code is a bit long-winded (am a newbie). I am sorry for the eyesore.

I am trying to return an "Error" if an argument is a string or array, the first if conditional always returns whether the arguments are numbers or strings of numbers instead of skipping it.

My line of thinking is if num1/num2 is a string then it evaluates to false and the NOT operator makes it true, thence completing the condition.

if (!(typeof num1 === Number) || !(typeof num2 === Number)) {
        return 'ERROR'; 
    }

But passing only numbers through still makes this condition true and returns it, which doesn't make sense since the if condition should be false and move over to the next line of code.

Could it be that I am equality checking a typeof operator to Number with an incomplete understanding of them that I am missing something?

Here is the rest of the code below:

const sumAll = function(num1, num2) {

  let sum = 0;

  if (!(typeof num1 === Number) || !(typeof num2 === Number)) {
    return 'ERROR';
  }
  if (num1 >= 0 && num2 >= 0) {

    if (num2 >= num1) {
      for (let i = num1; i <= num2; i++) {
        sum += i;
      }
    } else {
      for (let i = num2; i <= num1; i++) {
        sum += i;
      }
    }
    return sum;
  } else if (num1 < 0 || num2 < 0) {
    return 'ERROR';
  }
};

sumAll(1, 4)
depperm
  • 10,606
  • 4
  • 43
  • 67
M Codet
  • 57
  • 5
  • 2
    `typeof num1 === Number` will always be `false` because `typeof` returns a string. The correct way is to test `typeof num1 === "number"`. If you want to check for instances of the Number class, then you need `num1 instanceof Number`. However that will be `false` for primitive numbers. – VLAZ Mar 16 '23 at 10:45
  • Wow. Thank you so much. Never would have realized the typeof lapse in understanding. @VLAZ – M Codet Mar 16 '23 at 11:39

0 Answers0