Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to run code inside the conditional operator?

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:

  • Is this thing error-free and safe to use? (like, with a lot of code inside, and nested stuff)

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.

like image 460
ajax333221 Avatar asked Dec 09 '22 03:12

ajax333221


1 Answers

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.

like image 122
Rob Hruska Avatar answered Dec 27 '22 18:12

Rob Hruska