1

Why are const declarations within a while loop not an issue? Isn't the same variable being redeclared in each iteration?

In the code below, the arrValue variable is declared within the loop. I felt this would be an issue but it runs fine without errors.

Usually, I would have declared the let arrValue; right before the loop and accessed it within the loop without having it redeclared.

const arr = [1, 2, 3, 4, 5];
let sum = null;
while (arr.length > 0) {
  const arrValue = arr.pop();
  sum += arrValue;
}
console.log(sum);
4
  • const (and let) are block scoped variables Commented Aug 22, 2022 at 3:36
  • I would have declared the const arrValue; right before the loop - which would cause your code to fail since a) you need to assign a value when declaring a const and b) you would then try to assign a new value to a const - which would fail, as const is a constant value Commented Aug 22, 2022 at 3:37
  • I thought block scoped means that you cant access the variable OUTSIDE of the block. And yes, i would have to use let declaration before the while statement. Commented Aug 22, 2022 at 3:44
  • Yes, that's what it means - it also means that it's a "new" variable for each iteration Commented Aug 22, 2022 at 3:50

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.