-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));
deceze
  • 510,633
  • 85
  • 743
  • 889
  • 3
    `myArr.length != []` -> `myArr.length != 0` – VLAZ Jul 12 '21 at 11:38
  • 4
    `myArr != []` is always true, since an object is never equal to another object. – deceze Jul 12 '21 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);` – VLAZ Jul 12 '21 at 12:23

1 Answers1

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));
mplungjan
  • 169,008
  • 28
  • 173
  • 236