6 of 17 menu

The Error of Iterating an Array with For-in Loop in JavaScript

To iterate over an array, you should use the for-of loop. Sometimes, however, beginners mistakenly try to use the for-in loop. Let's look at the characteristic signs of this error.

Let's say we have an array:

let arr = ['a', 'b', 'c'];

Let's iterate over the elements of this array and write them into a single string.

A certain programmer has already solved this task, but mistakenly used a for-in loop. Let's see what they got:

let res = ''; for (let elem in arr) { res += elem; } console.log(res); // will output '012'

So, the result is the string '012', not 'abc'. Let's figure out why this happened.

Why was the array even iterable via the for-in loop? The point is that an array in JavaScript is a specific case of an object. Therefore, in this regard, this is actually valid code. But it should not be done this way.

The point is that for-in under certain conditions can pick up extra properties, and besides the array elements, you might get something parasitic during iteration. Only iterate arrays using for-of.

Now let's understand why we see such a strange result. The point is that when iterating with for-in, the variable elem will actually receive the keys, despite the misleading name of this variable.

Let's fix the mistake that was made and write the correct code:

let arr = ['a', 'b', 'c']; let res = ''; for (let elem of arr) { res += elem; } console.log(res); // will output 'abc'
English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline