I am currently working on a function that is supposed to return an Array when the condition is true and a string when it's false. Initially, I wrote the code like this:
return (myArr != []) ? myArr : `${integer} is prime`;
However, when myArray is empty, instead of getting the output as ${integer} is prime
, I receive an empty array []
.
When I changed it to return (myArr.length != 0) ? myArr : `${integer} is prime`;
, it worked fine, but I am not sure why.
Below is my code:
function divisors(integer) {
var i = 2;
var myArr = [];
do {
(integer % i) ? null : myArr.push(i);
i++;
} while (i < integer);
return (myArr.length != 0) ? myArr : `${integer} is prime`;
}
console.log(divisors(42));