Reputation: 3737
I just came across this code on the Mozilla site and, while to me it looks broken, it's likely I am not familiar with its use:
for (; k < len; k++)
{
if (k in t && t[k] === searchElement)
return k;
}
How does the semicolon work at the beginning of the loop?
The full code is here.
Upvotes: 6
Views: 3881
Reputation: 26819
it's mean that declaration and initialization k variable is something upper;
If you want skip some for section, you just put semicolon, e.g.:
for (;;) {
//infinite loop
}
Upvotes: 2
Reputation: 655469
The first part is the initial-expression that is used to initialize variables (see for
construct):
for ([initial-expression]; [condition]; [final-expression])
statement
The brackets mean in this case that it’s optional. So you don’t need to write any initializer expression if you don’t have any variables to initialize. Like in this case where k
is initialized before the for
loop:
var k = n >= 0
? n
: Math.max(len - Math.abs(n), 0);
for (; k < len; k++)
{
if (k in t && t[k] === searchElement)
return k;
}
You could also write it as initial-expression part but that wouldn’t be that readable:
for (var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); k < len; k++)
{
if (k in t && t[k] === searchElement)
return k;
}
Upvotes: 14