Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

174
Views
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;
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!