Reputation: 375
If I combine these 2 statements:
x = 1+1;
y = (x<1)? x : 0;
to be one statement:
z = (1+1<1) ? 1+1 : 0;
Is the evaluation cached such that there would not be a performance hit?
Asked a different way, is there a way, using one variable, to use the value calculated if it meets a condition, or if not, set a value?
Upvotes: 0
Views: 41
Reputation: 664579
Is the evaluation cached such that there would not be a performance hit?
No, you've duplicated the code, so it will be evaluated twice. JS does not do any common subexpression elimination in general.
Is there a way, using one variable, to use the value calculated if it meets a condition, or if not, set a value?
No, except for using a function (that internally can refer to its parameter multiple times). Assuming you meant <= 0
when you wrote < 1
, you could e.g. do
var y = Math.max(1+1, 0);
Upvotes: 1