Why using const in a for loop does not throw an error
P粉244155277
P粉244155277 2023-09-08 16:14:20
0
1
508

const todolist= [];
let todolisthtml = '';
     for(let i =0;i<todolist.length;i++){
          const todo = todolist[i];
          const html = <p>`${todo}`</p>;
          todolisthtml += html;
      }

Here, whenever we iterate through the loop, we are reassigning the variable todo, which should cause an error because we declared it using "const", but it works smoothly

P粉244155277
P粉244155277

reply all(1)
P粉277305212

This is not a task. Just declaration and initialization.

If you write

const todolist= [];
let todolisthtml = '';
const todo;
for(let i =0;i<todolist.length;i++){
    todo = todolist[i];
    const html = <p>`${todo}`</p>;
    todolisthtml += html;
}

This would be a reallocation and is illegal.

In what you wrote, todo and html go out of scope at the end of the loop block, followed by a new todo and html is created for the next iteration.

As Jaromanda X said, const variables are block scoped. And let.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template