8

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?
Luigi
  • 4,129
  • 6
  • 37
  • 57
user3439515
  • 123
  • 4
  • 7
    I think the biggest issue is just readability. It is much easier to look at the if statement and figure out what is happening. – Jeff Shaver Apr 21 '14 at 19:15
  • 1
    If you love Star Wars, Yoda code is always great, putting the string in front of the typeof check in front of the assignemnt etc. – adeneo Apr 21 '14 at 19:17
  • I always think of [KISS](http://en.wikipedia.org/wiki/KISS_principle). – The Alpha Apr 21 '14 at 19:17
  • 1
    possible duplicate of [Using &&'s short-circuiting as an if statement?](http://stackoverflow.com/questions/5049006/using-s-short-circuiting-as-an-if-statement), [Difference between “if (foo) bar();” and “foo && bar();”](https://stackoverflow.com/questions/17907997/difference-between-if-foo-bar-and-foo-bar) and a few others – Bergi Apr 21 '14 at 19:19
  • 1
    That actually looks much like minified code. Are you sure you're reading the actual source file? – Bergi Apr 21 '14 at 19:21
  • This is just confusing and unnecessary IMO. I am all about terse code but not just for the heck of it. – Sethen Apr 21 '14 at 19:24
  • @Bergi Does minification convert if statements to this format? – user3439515 Apr 21 '14 at 19:30
  • @user3439515: I remember some minifiers to do that, yes - it saves characters. – Bergi Apr 21 '14 at 19:34

1 Answers1

5

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).

djechlin
  • 59,258
  • 35
  • 162
  • 290