zaggi
zaggi

Reputation: 940

JavaScript: How to simultaneously declare a var and let variables in a for loop

Although a hypothetical, this case puzzled me. Do you think it's possible and if so - how

function count() {

    for (
        let i = 0, k = 0; // <<< can this become sth like 'var i = 0; let k = 0' ?
        i < 10; 
        i++, k++ 
    ) { 
        ...
    }

     // ... so that these log as follows:
     console.log( i ); // 10
     console.log( k ); // undefined or Error
}

count();

Note: It's ok to declare for (let i=0, k=0; ...) or for (var i=0, k=0; ...), but can the i and k be declared simultaneously via var and let respectively somehow ?

Upvotes: 1

Views: 99

Answers (2)

Bergi
Bergi

Reputation: 664538

No, this is not allowed by the grammar. You can only have one of the keywords var, let and const in a loop head (or none at all).

The solution is to just put the var outside of the loop head, which is a good practice anyway if you want to use it after the loop:

function count() {
    var i = 0;
    for (
        let k = 0;
        i < 10; 
        i++, k++ 
    ) { 
        …
    }

    console.log( i ); // 10
    console.log( k ); // ReferenceError
}
count();

Upvotes: 3

James
James

Reputation: 22247

Declare the function-scoped variable outside the for loop. This kind of happens anyway when you use var keyword within a for loop for (var i=...), the declaration gets hoisted. Then you are free to use let within the for loop to get block-level scope. You could even use let for both declarations since they are now not relying on the hoisting provided by var.

function count() {
    var i = 0;
    // or let i = 0;
    for (
        let k = 0;
        i < 10; 
        i++, k++ 
    ) { 
        // 
    }

     // ... so that these log as follows:
     console.log( i ); // 10
     console.log( k ); // undefined or Error
}

count();

Upvotes: 2

Related Questions