Reputation: 2339
I want to ask about optimisation in JavaScript if else
statement.I have the code like this
if ( thisIsTrue )
printMe("someMessage");
And the code can be optimisation like this
thisIsTrue && printMe("someMessage");
The question is what the code of thisIsTrue && printMe("someMessage");
only works in statement who has been return true.
What if the return is false?
Upvotes: 1
Views: 723
Reputation: 18568
Although this is not optimisation and not suggested but i would explain the details.
in a combination of operands like A && B
, 1st
the operand A
will be executed and if it return true
the second operand
will be executed otherwise it will be terminated because if the 1st operand
is true
the result
will depends on the second operand
else if the 1st
is false
result
will surely be false
irrespective of the second operand so it doesnot execute the second one. so
true && alert("someMessage"); will show alert
and
!false && alert("someMessage....."); will also show
combinding the above two, you can write is as
condition ? alert("someMessage") : alert("someMessage.....");
fiddle : http://jsfiddle.net/9q2jC/1/
Upvotes: 2
Reputation: 19027
If you have a series of If-Then-Else statements, you should try your best to organize them from most likely to least likely. This way the program doesn't have to traverse all the unlikely conditions to get to the likely ones, which will be called more often.
A commonly used tactic to wring whatever overhead might be left out of a large group of simple conditional statements is replacing If-Then-Else's with Switch statements. This is a tough one to qualify. Performance varies widely, although you almost always come out with some kind of improvement, even if it is small. As always, proper code design is much more important. See there are good test cases with switch and if elseif else
Upvotes: 1
Reputation: 28349
You should avoid turning your code into a puzzle either for someone else, or for the future you. There is nothing to be gained from mixing your conditions with your output. It's not going to "optimize" anything, and it will cost you lots of time in the future as you try to debug this.
I would argue you should err on the side of MORE verbosity not less.
Upvotes: 13
Reputation: 230336
This is hardly an optimisation (in terms of performance).
Also, these two forms are not identical.
The latter is an expression, while the former is a statement.
Upvotes: 1