Skip to content Skip to sidebar Skip to footer

Using '&&' As A Shorthand If Statement?

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 va

Solution 1:

This doesn't work because the && operator has higher precedence than the = operator. In other words, your code is interpreted like this:

(var1 == 5 && var2) = 2; 

If you manually put parentheses around the assignment, it will be interpreted correctly.

var1 == 5 && (var2 = 2); 

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 if statements, like this

if(condition) statement;

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

Solution 2:

Don't be alarmed that this doesn't work as you'd expect, in fact less than a month ago Brendan Eich (Creator of JavaScript) was sharing with us that this type of use is better known as an "abusage" of the language, since this logical operator isn't meant to execute code like this, but rather it's meant to determine the value of an expression.

"I also agree...that the && line is an abusage, allowed due to JS’s C heritage by way of Java, but frowned upon by most JS hackers; and that an if statement would be much better style..." http://brendaneich.com/2012/04/the-infernal-semicolon/

That being said, you can avoid the operator precedence issue by wrapping your statements:

(var1 == 5) && (var2 = 2)

Solution 3:

because you are using an invalid operator on the right-hand side. its trying to read the entire statement as a single variable.

Post a Comment for "Using '&&' As A Shorthand If Statement?"