0

I'm coming to javascript from a python background and wanted to ask about how to interpret some code i see.

In Python, I can get the following code/output:

Python Code:

myarray = ["a","b", "c"]
for item in myarray:
   print (item)

Python Output

a
b
c

In Javascript, this gives me something different:

Javascript Code:

var myarray = ["a","b","c"]
for(var item in myarray){
  console.log(item)
}

Javascript Output:

"0"
"1"
"2"

It's this interpretation that's confusing me. In python, the for loop naturally reads "for every item in myarray, print item". However in the Javascript version, it prints out "0", "1", "2". To get it correct, I would need to change the code to be:

var myarray = ["a","b","c"]
for(var item in myarray){
  console.log(myarray[item])
}

I wanted to ask what is the logic behind this as (at least to me, it doesn't seem as clear)? Also, why would my first way print the items out as strings?

Thank you for your help!

user1357015
  • 11,168
  • 22
  • 66
  • 111
  • 1
    Different languages operate differently, sometimes you need to read the documentation to understand how and why. **What is the question here?** –  Dec 10 '13 at 04:03
  • possible duplicate of [Loop through array in JavaScript](http://stackoverflow.com/questions/3010840/loop-through-array-in-javascript) – John Dec 10 '13 at 04:03
  • [this question](http://stackoverflow.com/questions/3010840/loop-through-array-in-javascript) may be useful – loopbackbee Dec 10 '13 at 04:03

3 Answers3

3

Your JavaScript code shows a means of iterating an Array that should rarely be used. You should use a for statement.

var myarray = ["a","b","c"]
for(var i = 0; i < myarray.length; i++){
  console.log(i, myarray[i])
}

The reason is that for-in is a general property enumerator. It includes all properties of the object, both owned and inherited, and isn't constrained to numeric indices. As such, it will include all owned or inherted enumerable properties that you may have included.

Additionally, for-in makes no guarantees of the order of enumeration. Therefore, you can't be certain that you'll get a desired ascending sequence.


All keys of Objects in JavaScript are strings, and Arrays are just another type of Object. That's why for-in gives you strings for its keys, and that's why a for-in works on Arrays.

Typically the for-in would be used for Objects, as in:

var myobject = {
    foo: "bar",
    baz: "buz"
}

for (var p in myobject) {
    console.log(p, myobject[p]);
}

So yes it "works", in the sense that the for-in statement doesn't reject the Array object. But if the goal is to have an iteration of numeric indices in a predictable sequence, then for-in just isn't the right tool.


If you're simply after a nicer syntax, ECMAScript 5 added several Array iteration methods that accept a callback function that is invoked for each existing member.

The .forEach() method is one example.

myarray.forEach(function(item, i) {
    console.log(item, i);
});
Blue Skies
  • 2,935
  • 16
  • 19
  • Why though? I totally understand why I can do this with a for loop for i – user1357015 Dec 10 '13 at 04:03
  • Care to explain why it shouldn't be used? –  Dec 10 '13 at 04:05
  • 1
    Read this answer: (It is truly excellent): http://stackoverflow.com/a/2891043/588079 Then understand array's and why you don't use for in!! It's not worth posting me an answer if it was answered so perfectly – GitaarLAB Dec 10 '13 at 04:07
  • Thank you for this. This was excellent. @GitarrLab, that reference is great! Much appreciated. – user1357015 Dec 10 '13 at 04:16
0

A for...in loop does not iterate over non–enumerable properties. Objects created from built–in constructors like Array and Object have inherited non–enumerable properties from Object.prototype and String.prototype that are not enumerable, such as String's indexOf method or Object's toString method. The loop will iterate over all enumerable properties of the object itself and those the object inherits from its constructor's prototype (properties closer to the object in the prototype chain override prototypes' properties).

A for...in loop iterates over the properties of an object in an arbitrary order (see the delete operator for more on why one cannot depend on the seeming orderliness of iteration, at least in a cross-browser setting). If a property is modified in one iteration and then visited at a later time, its value in the loop is its value at that later time. A 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 general it is best not to add, modify or remove properties from the object during iteration, other than the property currently being visited. There is no guarantee whether or not an added property will be visited, whether a modified property (other than the current one) will be visited before or after it is modified, or whether a deleted property will be visited before it is deleted.

yan
  • 11
  • 2
0

Try this -:

for(item in myarray){
  console.log(myarray[item])
}

item will get index of myarray.

Nilesh
  • 2,407
  • 1
  • 12
  • 20