-1

I'm writing a function that should return Array when it's true and a string when false I first wrote like this : return (myArr != [])? myArr:`${integer} is prime`; but when myArry is empty, istead of receiving ${integer} is prime I get an empty arr [], When I write return (myArr.length != [])? myArr:`${integer} is prime, it works, and I dont understand why?

below my Code :

function divisors(integer) {
  var i = 2;
  var myArr = [];
  do {
    (integer % i) ? null : myArr.push(i);
    i++
  } while (i < integer);
  
  return (myArr != []) ? myArr : `${integer} is prime`;
}

console.log(divisors(42));

3
  • 3
    myArr.length != [] -> myArr.length != 0 Commented Jul 12, 2021 at 11:38
  • 4
    myArr != [] is always true, since an object is never equal to another object. Commented Jul 12, 2021 at 11:42
  • Not sure why the do..while or even the conditional expression. This seems like the job for a bog standard loop for (let i = 2; i < integer; i++) and the body is a simple if (integer % i === 0) myArr.push(i); Commented Jul 12, 2021 at 12:23

1 Answer 1

0

You cannot test an array == [] to see if it is empty - see comments to your questions

Perhaps you meant this

function divisors(integer) {
  var myArr = Array.from(Array(integer),(x,i)=>i).filter(int => integer%int===0)
  return (myArr.length>1 && myArr[0] === 1) ? myArr : `${integer} is prime`;
}

console.log(divisors(42));
console.log(divisors(11));
console.log(divisors(12));
console.log(divisors(997));

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.