Search code examples
javascriptoperatorsconditional-statementsor-operator

How javascript || (or) operator works


In the following JavaScript statement:

var a = true;
a = a || b;

Will the a variable have an unneeded reasignment to it's own value?


Solution

  • 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.