Processing data in a loop "for" results in an error

When processing data from ther response in json in a for loop,

JSON:

{
 "languages": [
        {
            "id": 1,
            "name": "English",
        },
        {
            "id": 2,
            "name": "Norwegian",
        },
        {
            "id": 3,
            "name": "Dutch",
        },
        {
            "id": 50,
            "name": "French",
        },
        {
            "id": 76,
            "name": "Inuktitut",

        }
    ]
}

TEST:

   var jsonData = JSON.parse(responseBody);
   var lng_count = jsonData.languages.length;
   for (i=0;i<=lng_count;i++){
       console.log(jsonData.languages[i].id);
   }

I faced a problem that the test fails with an error
ERROR:
TypeError: Cannot read properties of undefined (reading 'id').

but when i do it in “while” it works as expected

var jsonData = JSON.parse(responseBody);
var lng_count = jsonData.languages.length;
i = 0;
while (i < lng_count){
    console.log(jsonData.languages[i].id);
}
i++;

Can anybody explain what is wrong with loop “for” ?

Hi @TestQA2019

Because your ‘for’ is set as “less than or equal to length” but your while is set as “less than length”.

.length would tell you how many items (5 in your example) but the for loop would be 0,1,2,3,4 …
(the equal to 5 part of your for would be looking for the 6th item)

So as an example:

What you would need is the for loop to stop before it gets to the 6th item, you would do this by only stating less than length, instead of less than or equal to length:

for (i = 0; i < lng_count; i++){

And the reason your while loop works is because it is already set as less than (not less than or equal to) length.

1 Like

yes, you are right. Thx !!!