verism
verism

Reputation: 1164

Is it possible to have a conditional third expression in a for loop?

I'd like to know whether the third argument (statement/expression?) in a for loop can be conditional. For example, if a function were to be invoked with an optional third argument, the presence or absence of this optional argument would determine the third operation.

function doThing(arg1, arg2, optional) {
    var args = arguments;
    for (var i = arg1; arg1 < arg2; args[2] ? i = i+optional : i++) {
        // Do stuff
    }
}

I can't find anything relating to this online, so I'm guessing probably not; if not what would be the best way to create the same functionality?

Upvotes: 1

Views: 141

Answers (4)

p.s.w.g
p.s.w.g

Reputation: 149010

Yes you can do that, but it would require re-evaluating args[2] on every iteration, which can be a bit inefficient. I'd recommend a slightly different alternative:

function doThing(arg1, arg2, optional) {
    var inc = optional || 1;
    for (var i = arg1; arg1 < arg2; i += inc ) {
        // Do stuff
    }
}

This way you've only have to determine the inc value (how much to increment i by in the loop) once, then you can reuse that value throughout the rest of the function.

Upvotes: 1

zerkms
zerkms

Reputation: 254916

As per http://www.ecma-international.org/ecma-262/5.1/#sec-12.6.3

IterationStatement : for ( ExpressionNoIn opt ; Expression opt ; Expression opt ) Statement

You can see that the third argument for for is an expression. So anything that is a valid expression can be used there.

args[2] ? i = i+optional : i++ is a valid expression.

I'd rather specify it as:

i += args[2] ? optional : 1

Upvotes: 4

Barmar
Barmar

Reputation: 780871

You can do:

var step = (optional === undefined ? 1 : optional);
for (var i = arg1; i < arg2; i += step) {
    ...
}

Upvotes: 4

Mr. Llama
Mr. Llama

Reputation: 20889

No, but you can always rewrite the for loop by leaving out the increment and manually handling it inside the loop:

for (var i = arg1; arg1 < arg2; ) {
    // Do stuff

    if (condition) {
        i = i + optional;
    } else {
        i++;
    }
}

Your case, however, can be simplified rewritten as:

for (var i = arg1; arg1 < arg2; i += (condition ? optional : 1))

If the logic is more complex then simple increment, then using the first example would be better.

Upvotes: 2

Related Questions