Search code examples
for-loopsquare-bracket

Why is the initializer of for loop enclosed in square brackets?


for (let i=0; i<select.options.length; i++) {
    if(selectObject.options[i].selected) {
        numberSelected++
    }
}

Is it necesarry to put a square brackets to access the initializer in the loop?


Solution

  • Yes, Cleaner and less error-prone code (just like you ask) exists.

    const optionsIterator = select.options.values();
    
    for (const oneOption of optionsIterator) {
        if(oneOption.selected) {
            numberSelected ++
        }
    }