javascriptwhile-loopassignment-operator

Is an assignment expression in a 'while' condition a bad practice?


This article explains why I have a warning if I use code like this:

var htmlCollection = document.getElementsByClassName("class-name"),
    i = htmlCollection.length,
    htmlElement;

// Because htmlCollection is Live, we use a reverse iteration.
while (htmlElement = htmlCollection[--i]) { // **Warning?! Why?!**
    htmlElement.classList.remove("class-name");
}

But this doesn't have an explanation about why is a bad practice to assignment expression in a while condition.

I also read these Stack Overflow answers that point this practice as good. So...

Is there a performance problem with while (element = element.parentNode) syntax-wise or is it just a code style recommendation?


By the way, seems the --i operator is also a bad practice. I read in this article:

The ++ (increment) and -- (decrement) operators have been known to contribute to bad code by encouraging excessive trickiness.

Is it some sort of joke?


Solution

  • There shouldn't be any performance problems with it (arguably, indexing with prefix increment can be slightly slower than postfix increment, due to issues with CPU pipelines; this is a micro-optimization so ridiculously micro that it almost certainly means nothing in the context of JavaScript engine overhead. Even in C, the compiler is likely to reorder expressions if it can to ensure it's not stalled waiting on the increment).

    Either way, the main argument against assignment in a conditional is basically that most of the time when you do it, it's a mistake (you meant == or in JavaScript , ===). Some code checkers (and C# requires this as a language feature to avoid accidents) are satisfied if you wrap the assignment in an additional layer of parentheses, to say, "Yup, I really meant to assign" (which is also necessary when you're comparing the result of the assignment to some other value; omitting the parentheses would instead compare, and then assign a Boolean value, which even more likely to be wrong).

    Some people have a hate on for increment/decrement operators used as part of larger expressions, because remembering the order of operations is hard I guess, and because C programmers have been known to write horrible things like ++*++var and the like. I ignore these people; just don't use it for excessively tricky things.