What will be the default type of the variable in for..of loop.
for (value of [1,2,3]) // what is the default type of value
console.log(value)
I want to know whether value
type will be var/let/const.
As far I know any undeclared variable will be of type var
. Is it applies to for loop variables?
There is no default, though I guess you could call The Horror of Implicit Globals¹ in loose mode a kind of default. :-) Don't rely on the horror of implicit globals, it's effectively a bug in the language that's fixed by strict mode. :-)
If you write the code the way you have, you have to declare the variable prior to the loop. If you don't, in loose mode, a global var
is implicitly created; in strict mode (which I recommend using at all times), it's an error. If you declare the variable prior to the loop, either let
or var
(but not const
) will work.
If you declare the variable in the loop, you can use either let
or const
, depending on whether you want to update the variable in the loop (and also on your preferred style):
const values = ["one", "two", "three"];
for (const value of values) {
console.log(value);
}
for (let value of values) {
console.log(value);
}
for (let value of values) {
// (Note the following only changes the value of the variable, not the entry in the array)
value = value.toUpperCase(); // You couldn't do thsi with `const`
console.log(value);
}
¹ (that's a post on my anemic, neglected blog)