Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for ... in - Is the object being iterated evaluated just once before entering the loop?

When I use a for ... in loop like:

for(var i in object) {}

I want to know if the object in question is evaluated just once or each time the loop, well, loops.

I made a quick test in my browser (also in node) like:

for(var i in (console.log('INIT'), [1, 2, 3, 4])) { console.log('KEY', i); }

and I get:

INIT
KEY 0
KEY 1
KEY 2
KEY 3

So from this empirical evidence, I could assume that is indeed only evaluated once.

But, is this behavior standard?

like image 839
Ale Morales Avatar asked Feb 03 '26 16:02

Ale Morales


2 Answers

From the Mozilla documentation, a for...in loop will iterate over all enumerable properties of the object itself and those the object inherits from its constructor's prototype. An (enumerable) property that is deleted before it has been visited will not be visited later. Properties added to the object over which iteration is occurring may either be visited or omitted from iteration.

In short, the outcome of the example posted by @Amit is not guaranteed, although Chrome and IE may use a different specification for the for ..in loop. However, at least deleting an element seems to prevent it from being visited in Chrome:

var obj = { a: 1, b: 2, c: 3 };

for(var k in obj) {
  document.write(k);
  delete obj['c']; 
}
like image 66
Alex Avatar answered Feb 05 '26 06:02

Alex


Bear in mind that (console.log('INIT'), [1, 2, 3, 4]) is an expression that evaluates to [1, 2, 3, 4] so it's not a valid evidence of the issue. A better empirical evidence can be obtained with:

var obj = { a: 1, b: 2, c: 3 };

for(var k in obj) {
  document.write(k);
  obj.d = 4;
}

And we don't see "d"...

like image 37
Amit Avatar answered Feb 05 '26 06:02

Amit