tags:

views:

47

answers:

3

Hello

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

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

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

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

which works. Is this behaviour expected?

Thanks, Rene

+1  A: 

Yes, it is.

If you want to, you can use a for loop, like this:

for (var b; b = a.pop(); ) {      //Note the final semicolon
    do_sth(b);
}
SLaks
+3  A: 

JavaScript doesn't have block scope. So all var declarations are at function scope. So declaring a variable in a while expression doesn't make sense in JavaScript.

Additionally, you should end your statements with a semicolon. It's not strictly necessary, but it's highly recommended.

Daniel Pryden
+3  A: 

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.

Nosredna