Search code examples
javascriptfor-loopsyntax-errorfor-in-loop

Why for-in loops can't have multiple variable declarations?


let example = {
a:20,
b:40,
c:60
}

for(let j=0,i in example){
console.log(example[i]*j);
j++;
}

Why normal for loop can have multiple variable declarations, but for-in loop cannot? Or am I doing this somehow wrong?


Solution

  • I can understand the frustration, you're using the same keyword so why doesn't it behave similar? But I think you should think about it this way:
    for is a way to define a loop, for as long as some condition is true, with different way for how to define that condition.

    In a regular for loop, you loop as long as the middle part (the condition) is true:
    for(let i = 0; i < 10; i++)

    This is similar to how a while loop might work, but it's a syntactic short cut:

    let i = 0;
    while (i < 10) {
        i++;
    }
    

    So the for..in is a for loop that has another sort of condition, for every property in this object, so as long as you have more properties it will keep looping. You could write that like this as well:

    const keys = Object.keys(example);
    for (let i = 0; i < keys.length; i++) {
        const key = keys[i];
        const value = example[key];
    }
    

    You also have for...of, which loops over items in a array, but that is syntactic sugar for:
    for(let i = 0; i < array.length; i++) { const item = array[i]; }

    Also consider how a do...while loop is like a while loop but with some slightly different rules and behavior. Rather than getting frustrated with the syntax try to understand how it's saving you time by making your code a little less wordy, but in order to do that it needs to be a little different for each case. The alternative would be to have very many language keywords.