javascript – Why is developing this function with ternary operator wrong?

Question:

function numeroPositivo(numero) {
    //modificar debajo de esta línea
 
    return (numero > 0) 
  ? "Es positivo" 
    : "Es negativo" 
      ? numero === 0
        : false;
}

The function receives an integer and I have to return a string that says if it is positive, negative and if it is zero return false

I want to know why this ternary operator is wrong and how can I do it right, I don't understand how to nest them, I know how to do it with if else , but I want to learn this way

Answer:

Your error is in the second ternary operator, since you have already finished the first one and a second cannot be accessed after the return

I suggest you use this operator

numero === 0 ? false : numero > 0 ? "Es positivo" : "Es negativo"

By first checking if the number is 0 and returning false , if not 0 , we access the second operator which will determine if the number is positive or negative

 function numeroPositivo(n) { return n === 0 ? false : n > 0 ? "Es positivo" : "Es negativo"; } console.log(numeroPositivo(1)); // Es positivo console.log(numeroPositivo(0)); // false console.log(numeroPositivo(-1)); // Es negativo
Scroll to Top