javascript – Why is the development of 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 I can do it right, I can'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 already finished the first and cannot be accessed a second after the return

I suggest you use this operator

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

Checking first if the number is 0 and returning false , if it is not 0 , we access the second operator that 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