Using && as a substitute for IF statement

I found the following code fragment when flashing the code:

"string" != typeof myVar && (myVar = "");

I understand what is happening here. If myVar is not a string, this first condition evaluates to true, so the second condition is true, causing myVar to be set to "". Therefore, it substantially replaces the following:

if ("string" != typeof myVar)
    myVar = "";

The only noticeable difference is that the first of the two strategies is also a return statement, although the code I found does not use the return value. Therefore, I wonder:

  • Are there any pros or cons to any strategy?
  • If the only pro for the first strategy is the ability to return value, is it a fragment that I consider unsatisfactory, since it is harder to read?
+4
source share
1 answer

I just want to point out that this idiom is less clear and understandable.

"string" != typeof myVar && (myVar = "");

I read this and actually had to convert it to if / else in my head. Steve McConnell argued that there would be one line of code for the work, which I tend to agree with, and that this was due to an absurd violation. Also note that the built-in side effects are primarily risky, which is pretty egregious.

parameters = parameters || {};
var speed = parameters.speed || 60;

IMO is much more understandable, in part because it is such a well-established idiom. or

if(x && x.employer && x.employer.company === 'google') 

is an explicit use of the idiom (you will get an exception if you do undefined.company, for example).

+2
source

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


All Articles