T.Chmelevskij T.Chmelevskij - 1 month ago 4
Javascript Question

"Uncaught reference" error in ES6 class when using `for of` in method

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.

Answer

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.

Comments