I often see and use codes like:
var myvar = (1 < 2) ? 3 : 4 ; //if 1 < 2 then myvar = 3, else = 4
But I just recently saw a code that was executing code, just like some kind of replacement for the if(){}else{}
:
Example:
(1 < 2) ? alert("example1") : alert("example2");
The first thoughts that came to me were, "wow, this is like 6-7 characters shorter", "endless of possibilities" or "this made my day".
My question:
For now, I will just keep using it in the normal way, I have the fear that if I start using it to execute pieces of code might not work.
Is this thing error-free and safe to use? (like, with a lot of code inside, and nested stuff)
Yes. However, the more code that's within it, the less readable it becomes.
I prefer to use it (the conditional operator) for short, concise statements. Anything more complex deserves an if/else
for the sake of readability and maintainability.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With