smilingwang
smilingwang

Reputation: 321

javascript for statement and operator in

There is a note in ecma-262 Specification:

The [In] grammar parameter is needed to avoid confusing the in operator in a relational expression with the in operator in a for statement.

so are there any ways to make

for (let i in x in y) {
   console.log(i);
}

print something ?

Upvotes: 0

Views: 64

Answers (1)

Bakkot
Bakkot

Reputation: 1245

Parentheses will make it parse more clearly:

for (let i in (x in y)) {
   console.log(i);
}

But it actually parses fine without them. The disambiguation is needed for the other kind of for loop:

for (let a = b in c; false;); // does not parse

for (let a = (b in c); false;); // parses fine

The reason your snippet isn't printing anything is that x in y always results in a boolean, so it's not going to print anything unless you've defined enumerable properties on Boolean.prototype or Object.prototype:

Boolean.prototype.foo = 'bar';
for (let a in ('' in {})) {
   console.log(a);
} // prints 'foo'

Upvotes: 2

Related Questions