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.

Answers:

Answer

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;
}
Answer

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
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.