22

Consider following code:

var arr = [111, 222, 333];
for(var i in arr) {
    if(i === 1) {
        // Never executed
    }
}

It will fail, because typeof i === 'string'.

Is there way around this? I could explicitly convert i to integer, but doing so seems to defeat the purpose using simpler for in instead of regular for-loop.

Edit:

I am aware of using == in comparison, but that is not an option.

6
  • Compare using == so no type check will be included Commented Jun 6, 2014 at 8:39
  • 1
    Simplicity is not the case here. You should use regular for loop for iterating arrays. Commented Jun 6, 2014 at 8:39
  • 1
    I'm just wondering if you know what kind of data is stored in i and why is a String Commented Jun 6, 2014 at 8:41
  • Simply don't use for…in enumerations on arrays! Just because a hammer is a simpler tool than an electric screwdriver, you shouldn't use it for screws. Commented Nov 10, 2016 at 0:15
  • Ruined 72 hours of my time for this!!! Commented Feb 24, 2021 at 14:41

5 Answers 5

18

You have got several options

  1. Make conversion to a Number:

    parseInt(i) === 1
    ~~i === 1
    +i === 1
    
  2. Don't compare a type (Use == instead of ===):

    i == 1 // Just don't forget to add a comment there
    
  3. Change the for loop to (I would do this but it depends on what you are trying to achieve):

    for (var i = 0; i < arr.length; i++) {
       if (i === 1) { }
    }
    
    // or
    
    arr.forEach(function(item, i) {
       if (i === 1) { }
    }
    

By the way you should not use for...in to iterate through an array. See docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

for..in should not be used to iterate over an Array where index order is important. Array indexes are just enumerable properties with integer names and are otherwise identical to general Object properties. There is no guarantee that for...in will return the indexes in any particular order and it will return all enumerable properties, including those with non–integer names and those that are inherited.

Because the order of iteration is implementation dependent, iterating over an array may not visit elements in a consistent order. Therefore it is better to use a for loop with a numeric index (or Array.forEach or the non-standard for...of loop) when iterating over arrays where the order of access is important.

Sign up to request clarification or add additional context in comments.

4 Comments

I did some reading, and I simply need to just stop using for in for arrays. It seems to be too easy to break unexpectedly.
Exactly, I think that forEach is a good replacement. Simple and also faster solution than for...i. You should use for...i only if you need to iterate trough an object.
forEach is not good if you're writing async code. The behavior of for...in for arrays is just stupid, it is NEVER what you want it to be. You can use for(const index of arr.keys()) {} as a drop-in replacement, but it seems to me that for...in should actually work properly.
Please use parseInt with the second parameter, 10. Consider using Number instead.
3

With === you compare also the type of values. Use == instead:

if ( i == 1 ) {}

or cast i to integer:

if ( +i === 1 ) {}

Also you can try with 'standard' for loop:

for (var i = 0; i < arr.length; i++) {
    if (i === 1) {}
}

Comments

3

If you don't need browser support below IE9, you can use Array.forEach

If you do, use the good ol' for (i = 0; i < arr.length; i++) {} loop.

Comments

0

Is this what you mean?

var arr = [1, 2, 3];
for(var i in arr) { //i is not the value of an element of the array, but its "attribute name"
    if(arr[i] === 1) {

    }
}

In any case, I'd use the good old classic for syntax, it's the recommended way to deal with arrays

1 Comment

No, the intent is to compare the index.
0

for-in loops properties in object, you could use for-of to loop array.

for (const i in [11, 22, 33, 44, 55]) {
    console.log(`${typeof i}: ${i}`);
}
string: 0
string: 1
string: 2
string: 3
string: 4

const obj = {
    11: 'a',
    22: 'b',
    33: 'c',
    44: 'd',
    55: 'e',
}
for (const i in obj) {
    console.log(`${typeof i}: ${i} -> ${obj[i]}`);
}
string: 11 -> a
string: 22 -> b
string: 33 -> c
string: 44 -> d
string: 55 -> e

for (const i of [11, 22, 33, 44, 55]) {
    console.log(`${typeof i}: ${i}`);
}
number: 11
number: 22
number: 33
number: 44
number: 55

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.