0

I was looking at source code of Ext object in ExtJs docs here and I noticed this for loop:

for (j = enumerables.length; j--;) {
    k = enumerables[j];
    if (config.hasOwnProperty(k)) {
        object[k] = config[k];
    }
}

So, normally in a for loop, we have do initialization, specify condition and then increment/decrement the counter. I do see an initial condition and j-- which decrements the counter after each iteration. However, what I can't figure out is how is the loop going to be terminated? I neither see any condition nor a break keyword that will terminate the loop.

What am I missing here?

1 Answer 1

2

the j-- is the loop condition, that's how it will terminate. the trailing ;) is the missing increment/decrement.

The j-- construct both decrements j and tests the old un-decremented value for non-zero to decide whether to continue looping. The loop stops when j is zero; below the loop, the value of j will be -1.

The key parts of the for loop to look for are the semicolons -- for ( ; ; ) Any valid expression (or comma-separated expression list) can go in any of the three slots, before, between, and after the semicolons.

The loop initializers go after the ( and before the first ;. The loop condition is the value of the expression between the two ; ;. The post-loop update goes after the last ; and before the ).

Sign up to request clarification or add additional context in comments.

5 Comments

That is correct. This approach is often used to improve the performance of a loop, to decrement the iterator toward 0 instead of incrementing it.
eg the classic C string copy loop: for ( ; *d++ = *s++ ; ) ; (with apologies to the original, which used while)
Why would the loop stop when j is 0?
Because 0 is implicitly converted to the boolean value false.
because the conditional tests (if, while, for, do) test for truthy, and 0, false, null, undefined, "" (empty string) (and in php, "0" string containing a single zero - go figure) are all "falsy"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.