Home  >  Q&A  >  body text

Why using const in a for loop does not throw an error

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粉244155277P粉244155277407 days ago460

reply all(1)I'll reply

  • P粉277305212

    P粉2773052122023-09-09 13:35:23

    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.

    reply
    0
  • Cancelreply