Search code examples
javascriptoperator-precedence

"Invalid left-hand side in assignment" on style property assignment


error unveils when this line is evaluated:

color && el.style.color = color;

what's going on? are DOM level 2 properties now a "read-only"?


Solution

  • The problem is precedence, you need parens:

    function log(msg, color) {
        var el = document.createElement('p');
        el.innerText = msg;
        document.getElementById('log').appendChild(el);
        color && (el.style.color = color);
    }
    

    && has higher precedence than = and so without the parens, you end up trying to assign to an expression (e.g., it effectively reads (color && el.style.color) = color;), which of course you cannot do.