Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why can "for in" use const in JS?

Tags:

javascript

const arr = [1, 2, 3]

for (let i = 0; i < arr.length; i++) { // can't use const
  console.log(i, arr[i]);
}

for (const i in arr) { // const is ok
  console.log(i, arr[i]);
}

Why can "for in" use const but "for" can't?

like image 352
weiheli Avatar asked Oct 28 '25 01:10

weiheli


2 Answers

You can't use const in the first loop because of i++ which will reassign the variable i.

In the for in loop, i can be a const because it is defined for each iteration.

like image 87
sjahan Avatar answered Oct 31 '25 09:10

sjahan


in the const element in arr the element is the same as element in the const element = arr[i] in the classical forloop. It is a constant variable with local scope, so it is declared and destroyed in each iteration.

like image 40
Tadeo Hepperle Avatar answered Oct 31 '25 09:10

Tadeo Hepperle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!