Which method is faster or more responsive in javascript, if-else, the ternary operator or logical OR? Which is advisable to use, for what reasons?
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
The conditional operator – also known as the ternary operator – is an alternative form of the if/else statement that helps you to write conditional code blocks in a more concise way. First, you need to write a conditional expression that evaluates into either true or false .
If condition is preferred in case if program requires executing only on true block. In this case, it is necessary to work around to use Ternary Operator. Nested Ternary Operator is not readable and can not be debugged easily. If else is more readable and easier to debug in case of issue.
In terms of speed there should be no difference. Unless you are using a really bad javascript implementation. The slowest part of both statements is the branching. Nice answer!
Seems like nobody did any actual profiling. Here's the code I used:
test = function() { for (var i = 0; i < 10000000; i++) { var a = i < 100 ? 1 : 2; /* if(i < 100) { var a = 1; }else{ var a = 2; } */ } } test();
Using the if
/else
block instead of the ternary operator yields a 1.5 - 2x performance increase in Google Chrome v21 under OS X Snow Leopard.
As one use case where this is very important, synthesizing real-time audio is becoming more and more common with JavaScript. This type of performance difference is a big deal when an algorithm is running 44100 times a second.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With