Question

I found the following snippet when digging through some code:

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

I understand what happens here. If myVar is not a string, that first condition evaluates to true so the second condition is evaluated, causing myVar to be set to "". So it's essentially a replacement for the following:

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

The only discernible difference is that the former of the two strategies is also a return statement, though the code I found is not using the returned value. So I'm wondering:

  1. Are there any pros or cons to either strategy?
  2. If the only pro for the first strategy is the ability to return a value, is the snippet I found considered poor programming since it is more difficult to read?
Was it helpful?

Solution

Just want to point out there are less clear uses of this idiom and more clear.

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

I read this and actually had to convert it to if/else in my head. Steve McConnell argued there shoud be one line of code per work, which I tend to agree with and which this is in ludicrous violation of. Also note that embedded side-effects are risky in the first place, this is pretty egregious.

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

is IMO a much clearer use, partly since it's such a well established idiom. or

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

is a clear use of the idiom (you'll get an exception if you do undefined.company, for instance).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top