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 reassign the variable todo which should cause an error as we used ‘const’ to declare it, but instead it is running smoothly
2
Answers
That isn’t an assignment. It is declaration and initialization.
If you had written
that would be reassignment, and would be illegal.
In what you have written,
todo
andhtml
go out of scope at the end of the loop block, then a freshtodo
andhtml
are created for the next iteration.As Jaromanda X says,
const
variables are block scoped. Andlet
, too.The use of
const
in thefor
loop you provided does not cause an error becauseconst
is used to declare variables that are block-scoped and have a constant value, meaning their value cannot be re-assigned once initialized. In your code, you correctly useconst
to declare the variablestodo
andhtml
inside the loop.The
const
keyword is not causing an error because it is not being used to declare the arraytodolist
. The array is declared usinglet
which allows re-assignment. In this case, you have initialized thetodolist
array as an empty array[]
, so there are no elements in it when the loop is executed.However, it’s important to note that since
todolist
is an empty array, the loop will not iterate over any elements, and therefore, the code inside the loop will not be executed. As a result, thetodolisthtml
variable will remain an empty string.If you want to add elements to the
todolist
array before the loop, you should do so before the loop starts. For example: