Is it safe to run code inside a conditional statement?

I often see and use codes such as:

var myvar = (1 < 2) ? 3 : 4 ; //if 1 < 2 then myvar = 3, else = 4 

But I recently saw the code that executed the code, just like a replacement for if(){}else{} :

Example:

 (1 < 2) ? alert("example1") : alert("example2"); 
The first thoughts that came to me were “wow, that sounds like 6-7 characters shorter,” “endless possibilities” or “it made my day.”

My question is:

  • Is this thing error-free and safe to use? (e.g. with lots of code inside and file attachments).

For the time being, I will continue to use it in the usual way, I have a fear that if I start using it to execute code fragments, it may not work.

+4
source share
4 answers

There are some exceptions. You cannot do this with:

  • break
  • continue
  • Any block, such as if , for , while , do or try

eg. What else, it can ruin your order of operations:

 x < 3 ? l = true : r = true; // Syntax error, = has lower precedence than ?: 

But this is not a reason not to do it, because it is ugly. Which one is clearer is:

 if(i > 5) { alert('One'); } else { alert('Two'); } 

or

 i > 5 ? alert('One') : alert('Two'); 

? This is not entirely true, is it? And preserving the characters is never a reason for anything, in fact; otherwise there would be no comments or spaces. A good minifier like the Google Closure Compiler will automatically convert them for you whenever possible, and there are many other places to save. In the end, this is what you find most convenient and readable.

In addition, if you need break , continue , etc., then it will be rather inconsistent and unattractive code.

+4
source

Is this thing error-free and safe to use? (e.g. with lots of code inside and file attachments)

Yes. However, the more code in it, the less readable it becomes.

I prefer to use it (conditional statement) for short, concise statements. Anything more complicated deserves if/else for readability and maintenance.

+7
source

You mean a three-dimensional operator . It is usually used to set variables using simple strings:

 var phone = old ? "blackberry" : "iPhone" 

This is much simpler than using if:

 var phone = "iphone" if (old) { phone = "blackberry" } 

Good in this context, in the example you described, and as soon as it starts to get confused, or I definitely do not recommend it!

An example might look like this:

 var msg = 1 < 2 ? "alert1" : "alert2"; alert(msg); 
+2
source

You can also write:

 alert( 1<2? "example1" : "example2" ); 

The ternary operand is intended for simple cases, sometimes developers get carried away and use it to replace several if..else statements, for example

 var someVal = foo < bar? 'yes' : bar > fum? : fum : fi != fee? fi : fee; 

which is not a good idea IMHO.

+1
source

Source: https://habr.com/ru/post/1389589/


All Articles