Chad
Chad

Reputation: 2455

How do I declare multiple vars in JavaScript's "for" statement?

for(var i = 0, var p = ''; i < 5; i++)
{
    p += i;
}

Based on a JavaScript book i'm reading, this is valid code. When I test it doesn't work, and in FireBug I get this error:

SyntaxError: missing variable name

Upvotes: 1

Views: 448

Answers (6)

user177800
user177800

Reputation:

you can't declare a variable in the second position termitation expression is the following works

var p;
for(var i = 0, p = ''; i < 5; i++)
{
    p += i;
}

Upvotes: 1

Brian Campbell
Brian Campbell

Reputation: 332986

Don't repeat the var, you only need it once in the declaration:

for (var i = 0, p = ''; i < 5; i++)
{
    p += i;
}

Upvotes: 2

Daniel Vassallo
Daniel Vassallo

Reputation: 344411

It looks like a typo.

You need to remove the second var and it will work perfectly:

for(var i = 0, p = ''; i < 5; i++)
{
    p += i;
}

Upvotes: 4

Marius
Marius

Reputation: 58949

remove the var from before p = ''.

Upvotes: 2

Gabe
Gabe

Reputation: 50503

var p = 0;
var i = 0;


for(i = 0; i < 5; i++)
{
    p += i;
}

or

for(var i = 0, p = 0; i < 5; i++)
{
    p += i;
}

Upvotes: 2

Quentin
Quentin

Reputation: 943833

var i = 0, var p = '';

should be

var i = 0, p = '';

the var keyword applies to the whole line.

Upvotes: 9

Related Questions