Reputation: 74550
In the following JavaScript statement:
var a = true;
a = a || b;
Will the a
variable have an unneeded reasignment to it's own value?
Upvotes: 2
Views: 154
Reputation: 50189
Yes it will assign to a
. This sort of thing probably wouldn't even be optimised in a compiled language.
It won't however waste time evaluating b
however as it knows the result already. Something like this happens when a = a || b
is run:
if a
a = a
else
a = b
EDIT:
To follow up what icktoofay said "it will not significantly impact performance.", it is simply setting a (boolean) variable which is one of the simplest operations that can occur. It will make little difference even if you're assigning to something more significant like a function or array as it will be assigning to a reference of the item, not creating it again.
Here is a performance comparison of doing nothing vs assigning to self (jsPerf link) thanks to @bfavaretto for setting it up.
Upvotes: 3
Reputation: 489
Yes - it won't be optimised away, because JavaScript doesn't optimise. Although the underlying parser implementation could conceivably optimise, I very much doubt it would in this case, and it would be very specific to the platform implementation.
Upvotes: 0
Reputation: 69663
a
will be true when a
or b
is true. So yes, unless you insert some more code between those lines which can affect the value of a
, the lower statement will always set a
to true.
Upvotes: 0