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.
It is preferable to use a semicolon before introductory words such as namely, however, therefore, that is, i.e., for example, e.g., or for instance when they introduce a complete sentence. It is also preferable to use a comma after the introductory word.
Semicolon is a legitimate statement called null statement * that means "do nothing". Since the for loop executes a single operation (which could be a block enclosed in {} ) semicolon is treated as the body of the loop, resulting in the behavior that you observed.
But observe carefully: the semicolon must be both preceded by a complete sentence and followed by a complete sentence. Do not use the semicolon otherwise: *I don't like him; not at all.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With