0

One of my co-workers created a silly bug in mongo mapreduce, he should have created an object but actually passed the string "{}". The weird thing was the script hasn't crashed but actually iterated over the string, so I did some investigation and found the following:

The script x="bla"; for (i in x) { alert(i); }; works the following way with different browsers:

  • IE(8): - (no alerts)
  • Chrome: 0 1 2
  • Firefox (an older one): 0 1 2 vBlength
  • Firefox 5: 0 1 2
  • MongoDB: 0 1 2 trim ltrim rtrim

I know perfectly well it's not a valid syntax, just pure curiosity, does anybody know why browsers behave the way they do? I'm especially interested in MongoDB's behaviour.

asked Jul 15, 2011 at 15:17

1 Answer 1

5

Actually, that is completely valid syntax.

Using the for...in loop in JavaScript will not only loop over arrays but also properties (i is simply an index, not an actual value in the array).

Check out the documentation at the Mozilla Developer Network:

for...in - MDN Docs

Their example should make things more clear.

answered Jul 15, 2011 at 15:19
Sign up to request clarification or add additional context in comments.

3 Comments

So basically I see the extra values because those properties aren't hidden?
@yi_H - Pretty much. You're seeing the differences in implementation details of both the for...in loop and the string object in the different browsers.
See Douglas Crockford's piece of advice about the for statement to avoid bad surprises.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.