Search code examples
javascriptwhile-loopassignment-operator

Assignment expression in while condition is a bad practice?


This article explains why I have a warning if I use a 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 no explaination about « why is a bad practice to assignment expression in a while condition? ».

I also read this stackoverflow answers that point this practice as good. So...

There is a performance problem with while (element = element.parentNode) syntax-like or is just a style-code recommandation?


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.

It's some sort of joke?


Solution

  • There should be no 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 microoptimization so ridiculously micro that it almost certainly means nothing in the context of JS 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 JS, ===). 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 parens, 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 parens would instead compare, then assign a boolean, 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 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.