¡Hola a todos! Tengo la siguiente duda, ¿por qué no puedo ejecutar esta línea de código dentro de una función?
function checkEqual(a, b) {
a < b ? return "Equal" : return "Not Equal";
}
checkEqual(1, 2);
Por otro lado, la siguiente línea sí es posible de ejecutar.
return a < b ? "Equal" : "Not Equal";
Sin embargo, debería poderse porque según el uso del operador ternario, si la condición no se cumple, se ejecuta el código que está después de los dos puntos.
¡¡Desde ya muchas gracias y saludos!!
1 Like
Sorry, my Spanish isn’t good enough…
That isn’t the right way to do that. Ternaries are not the same as if/else
. And if/else
does things, it does something in each branch. Usually you give it statements or code blocks.
A ternary doesn’t do that. A ternary, the whole thing, evaluates to something. So:
true ? 1 : 2
That whole thing essentially becomes 1
. It doesn’t “run” the 1
, the whole thing just evaluates to that. The problem is that return ...
is a statement, you are telling it to do something.
So, I couldn’t do this:
const foo = 1
foo === 1 ? return 'hey' : return 'there'
but I could do:
const foo = 1
return foo === 1 ? 'hey' : 'there'
because the second line will just become this:
return true ? 'hey' : 'there'
and then:
return 'hey'
To do what you wanted, it would have to be
if (a < b)
return "Equal"
else
return "Not Equal";
1 Like
Muchas gracias Kevin, me quedó clarísimo.
En ese caso, la siguiente lección estaría mal redactada. Dejo captura.
¡Muchas gracias y feliz año 2023!
1 Like