Reputation: 2139
I was trying to use for of
in one of my methods following ES6 syntax and run into Uncaught ReferenceError: item is not defined.
Message is obvious and I've fixed it.
My question is why do we have to explicitly declare variable when using it for looping in the method, but not in global scope? And why if we use variable implicitly declared in global scope it can be used in class afterwards?
Example:
var arr = ["a", "b", "c", "d"];
for(i of arr){
console.log(i);
}
class bar{
constructor(arr){
this.innerArr = arr;
}
// so how this one gets reference to outside i?
yell(){
for(i of this.innerArr){
console.log(i);
}
}
}
class baz extends bar{
// in here it's obviously fine because we have var ii
yell(){
let ii
for(ii of this.innerArr){
console.log(ii);
}
}
}
class foo extends bar{
// This gives Uncaught ReferenceError
yell(){
for(item of this.innerArr){
console.log(item);
}
}
}
var br = new bar(arr);
var bz = new baz(arr);
var f = new foo(arr);
br.yell();
bz.yell();
f.yell();
It just that it somehow feels counter intuitive.
Upvotes: 0
Views: 292
Reputation: 26828
The problem is not related to for of
. The ECMAScript specification states that
All parts of a ClassDeclaration or a ClassExpression are strict mode code.
And in strict mode you cannot access a variable that has not been declared yet.
As for why bar.yell()
can access i
: i
is already declared as global variable because of this code:
for(i of arr){
console.log(i);
}
That code runs in global scope in non-strict mode. Because of that i
is automatically declared as global variable.
Upvotes: 3
Reputation: 1535
If you want to use the variable in local scope, you must use the let
keyword. Please see https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Statements/let
The var keyword can be used and overwritten in global and local scope. I think this is because of the history of JavaScript.
Upvotes: 0