Caleb Libby
Caleb Libby

Reputation: 132

How can I remove the first part of a for loop?

For example, I have a variable that I've already defined that I want to use as a counter in a for loop. I've found that replacing the first expression with null works, but I was wondering if I could remove it entirely with a different version of a for loop.

Example:

function foo() {
    var i = 10;
    for(null; i > 0; i++) {
        console.log(i);
    }
}

Upvotes: 2

Views: 378

Answers (2)

Roman Muravchuck
Roman Muravchuck

Reputation: 41

function foo() {
    var i = 10;
    while(i++ > 0){
        console.log(i);
    }
}

But its never-ending loop =) You can use simply true:

while(true){
    ...
}

Upvotes: 1

Scott Marcus
Scott Marcus

Reputation: 65845

Just don't supply anything. All 3 parts of a for loop are optional.

function foo() {
    var i = 10;
    for(; i > 0; i++) {
        console.log(i);
    }
}

Upvotes: 11

Related Questions