简体   繁体   中英

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 ?

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();

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(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM