The question is a little dated, but I think the answers all miss an important distinction. That is, a while
loop expects an expression that evaluates to a conditional, i.e., a boolean or value that can be converted to a boolean. See Mozilla docs for details.
A pure assignment (without instantiation) is coerced to a boolean via its default return value (the value of the right-hand-side).
A var
(or let
or const
) is a statement that allows an optional assignment but has a return value of undefined
.
You can easily test this in your console:
var foo = 42; // undefined
bar = 42 // 42
The return values alone don't answer the question, since undefined
is falsey, but does show that even if JS let you put a var
in a conditional it would simply always evaluate to false.
Others have mentioned for
statements and that they allow declaration and instantiation of variables. This is true, but the documentation explains that for
expects a statement or assigment.
Opinions may vary, but for me all this adds up to an understandable consistency not a quirk in behavior with regard to loops. A while
loop is better thought of as a looping version of an if
statement than akin to a for
loop. If there is quirkiness in all of this, it's the for
statement's wholesale divergence from the language's normal syntax.