0

I have learned somewhere that variables declared using const throw error when reassigned. But inside a loop it works just fine.

For example;

for(let i=0; i<allItems.length; i++){
    const item = allItems[i]
    item.innerText = "Yayy"
}

This works fine, and does not throws error, eventhough item is reassigned multiple times. Can someone clarify why this happens.

  • You are not reassigning what `item` points to; you are merely changing a property of `item`. What item is pointing to can be changed/mutated, but if you were to try `item = 3` you would get an error. – Alexander Nied Aug 03 '22 at 03:37
  • @Phil - at a glance I also expected this to be a scope question, but actually the OP is confused regarding the difference between assignment and mutation; this probably should be closed for some different reason. – Alexander Nied Aug 03 '22 at 03:38
  • `const` is block-scoped. It can only be declared / defined / assigned once in a particular block – Phil Aug 03 '22 at 03:38
  • @AlexanderNied I'd wait for OP to clarify. They specifically pointed out the `for` loop as the source of confusion – Phil Aug 03 '22 at 03:39
  • @Phil - fair; on second read you're probably correct. Sorry about that. – Alexander Nied Aug 03 '22 at 03:40

0 Answers0