tags:

views:

204

answers:

4

Which method is faster or more responsive in javascript, if/else or the ternary operator? Is it preferred to use one or the other and if so, for what reasons?

+5  A: 

The speed difference will be negligible - use whichever you find to be more readable. In other words I highly doubt that a bottleneck in your code will be due to using the wrong conditional construct.

Andrew Hare
A: 

There is no difference in speed.

Some prefer the if/else for readability. Personally, I use the ternary operator whenever the logic is trivial enough to understand on one line.

SP
A: 

Advantage: more compact code.

Disadvantage: you have to make an assignment operation.

Robusto
+3  A: 

This is definitely premature optimization. If your page is slow, profile it and see why. If you're doing a zillion conditionals within a loop, refactor it. Probably the speed of the conditional is not your problem.

The choice should be made based on comfort and readability. If a conditional is "in-line", in a sense -- for example within a variable assignment -- a ternary operator can make sense. Otherwise if-then is usually clearer.

JacobM