Search code examples
javascriptfor-loopundefined

JavaScript for loop returning undefined


Why am i getting undefined for isPrime(2) in the below function? It's as if the whole if statement right after var result; is skipped for isPrime(2) but not for other inputs. I do not understand why this is so.

function isPrime(num) {
  if (typeof num !== "number") {
    throw "The input needs to be a number!";
  }

  var result;

  if (num <= 1) {
    result = false;
  } else {
    for (i = 2; i < num; i++) {
      if (num % i === 0) {
        result = false;
        break;
      } else {
        result = true;
      }
    }
  }

  return result;
}

Solution

  • If num is 2 then this part of a code will not be executed

    for (i = 2; i < num; i++) {
      if (num % i === 0) {
        result = false;
        break;
      } else {
        result = true;
      }
    }
    

    since i is initially 2 and num is 2, 2 < 2 is false.