René Nyffenegger René Nyffenegger - 2 months ago 7
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()) {
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

Answer

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.