Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the semicolon work at the beginning of "for"?

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.

like image 526
Stephen Avatar asked Mar 13 '11 12:03

Stephen


People also ask

Can you use a semicolon with for example?

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.

What does a semicolon in a for loop mean?

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.

Do you need a full sentence after a semicolon?

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.


1 Answers

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;
}
like image 92
Gumbo Avatar answered Sep 18 '22 12:09

Gumbo