René Nyffenegger René Nyffenegger - 1 year ago 97
Javascript Question

declaration for variable in while condition in javascript

In essence, I am trying to declare a variable in the condition-part of a while loop in javascript:

while (var b=a.pop()) {

Yet, my browser (firefox) doesn't accept that. Instead I have to go like so:

var b
while (b=a.pop()) {

which works. Is this behaviour expected?

Thanks, Rene

Answer Source

JavaScript does not have block scope. It has function scope. So to make sure that humans and JavaScript both read the code the same way, you should manually hoist your var declarations right up to the top of functions.

Here's what JSLint says about your code:

Problem at line 1 character 8: Expected an identifier and instead saw 'var'.

Use JSLint, at least while you're learning JavaScript. You'll learn a lot very quickly. It will hurt your feelings.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download