-1

I'm testing the for...in loop in javascript like this:

let test = ["hello"];

for (let index in test) {
  console.log(index);
}

With this example, in Chromium this prints something like this:

Chromium result 1

And in Firefox and Chrome the result is this:

Firefox and Chrome result 2

Can someone explain why get different outputs in this case?

  • In Chrome, I get your purported firefox result. – Jamiec Nov 24 '20 at 11:29
  • you are right, editing question, is in chromium xD – Ivan Caballero Nov 24 '20 at 11:31
  • [Why is using “for…in” for array iteration a bad idea?](https://stackoverflow.com/q/500504) although you *shouldn't* be getting this in Chrome. It seems like something on the page (or an extension) is changing the array prototype and exposing the exact problem the other Q&A shows. Although, given the names printed, it seems you're iterating over a Lodash wrapper or a similar library. – VLAZ Nov 24 '20 at 11:31
  • \*tsk tsk\* it seems it's our old friend (well, not really), [Prototype](https://www.tutorialspoint.com/prototype/prototype_enum_ingroupsof.htm) given the existence of an `inGroupsOf` method on the array. – VLAZ Nov 24 '20 at 11:33
  • Don't use for...in with arrays. – Jared Smith Nov 24 '20 at 11:58

1 Answers1

1

The reason seems to be that the page where you're trying this uncludes the Prototype framework. It has a very old school approach by enhancing the native prototypes in JavaScript to provide convenience methods.

let test = ["hello"];

for (let index in test) {
  console.log(index);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.7.3/prototype.min.js" integrity="sha512-C4LuwXQtQOF1iTRy3zwClYLsLgFLlG8nCV5dCxDjPcWsyFelQXzi3efHRjptsOzbHwwnXC3ZU+sWUh1gmxaTBA==" crossorigin="anonymous"></script>

This prints

0
each
eachSlice
all
any
collect
detect
findAll
select
grep
include
member
inGroupsOf
inject
invoke
max
min
partition
pluck
reject
sortBy
toArray
zip
size
inspect
_reverse
_each
clear
first
last
compact
flatten
without
uniq
intersect
clone

Compare with iterating over a normal un-enhanced array:

let test = ["hello"];

for (let index in test) {
  console.log(index);
}

This prints

0

The practice of changing the native prototypes has since become a frowned upon

VLAZ
  • 26,331
  • 9
  • 49
  • 67