0

How can the same 'const' be initialized multiple times in a for-loop? I thought 'const' can only be initialized once. I'm a beginning developer.

Does the const element get deleted each iteration and have to be redeclared? After a for-loop iteration loops each time, are all variables that were in its body deleted/lost?

const constDiv = document.createElement('div');

for (let i = 1; i <= 10; i++) {
    const element = document.createElement('p');
    element.textContent = 'This is paragraph number ' + i;

    element.addEventListener('click', function respondClick(event) {
        console.log('A <p> was clicked');
    });

    constDiv.appendChild(element);
}

document.body.appendChild(constDiv);
  • `const` is [**block scoped**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const#block_scoping). The body of the `for` loop is a block – Phil Feb 04 '22 at 01:40
  • Does this mean that after each iteration of the for loop, the const is deleted before it runs again? That way, each declaration is considered the first time it is being declared? – newprogrammer627 Feb 04 '22 at 01:46
  • 1
    "*Does the const element get deleted each iteration?*" - no, they persist as long as something is still referencing them. (In your case, nothing). "*Does it have to be redeclared?*" - yes, every iteration starts with a fresh, empty block scope. – Bergi Feb 04 '22 at 01:48
  • So as long as you have different block scopes, you can declare the same const over and over? like { const a = 5; } { const a = 7; } { const a = "string";} ? What do you mean by referencing? I thought you couldn't reference a const outside of its scope? As always - thank you for all the replies – newprogrammer627 Feb 04 '22 at 01:51
  • Yes, you can reference it only from within its scope, but for example if you had written `console.log('This was clicked:', element);` in your event handler, the variable would have been referenced by the function, which persists even after the loop ends. This is known as a [*closure*](https://stackoverflow.com/q/111102/1048572), and means the variables don't (necessarily) get destroyed at the end of each iteration. – Bergi Feb 04 '22 at 02:54
  • "*So as long as you have different block scopes, you can declare the same const over and over?*" - yes, exactly. They're different variables, with different values, with the same name but different scopes. – Bergi Feb 04 '22 at 02:56

0 Answers0