While I was killing time looking up Javascript shorthand patterns, I came across an interesting way of expressing an if statement here. The following works:
var var1 = 5;
var var2 = 1;
var1 == 5 && var2++;
I think that’s a totally cool (and shorter, cleaner) way of writing an if statement that only needs to do one operation. However, I ran into an issue with the following code as soon as I tried something else with it:
var var1 = 5;
var var2 = 1;
var1 == 5 && var2 = 2;
Instead of working like the first code snippet, my test throws an error:
Uncaught ReferenceError: Invalid left-hand side in assignment
Why doesn’t this work, and why is the left-hand side of my statement being called out as incorrect as opposed to the right hand?
This doesn’t work because the
&&operator has higher precedence than the=operator. In other words, your code is interpreted like this:If you manually put parentheses around the assignment, it will be interpreted correctly.
Other people will reprimand you for writing code like this, saying that is a bad idea because it makes the intent of the code harder to read–which is true, especially for people unfamiliar with this idiom–but it is important to try it out and experiment with things like this to see for yourself what happens. You’ve already encountered one of the annoying things about this approach.
Anyway, in cases like this, I personally prefer to use single line
ifstatements, like thisAlthough I’m sure others will tell you that that’s bad style because you have to manually add brackets when you need more statements, this hasn’t really bit me and IMO it’s cleaner than using three lines just for a simple condition, like you said.