Value comparison question | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Value comparison question

In the code below, in the second statement of both for loops. Why does i have to be smaller than personsPets.length in order to scan all elements of their respective arrays ? I don't quite get the logic behind this condition. For those of you who don't get it, the code is about finding the kind of pets two people have in common. var johnsPets = ["turtle", "dog", "parrot","cat"]; var amandasPets = ["cat", "goldfish", "dog"]; var petsInCommon = []; for(i = 0; i < johnsPets.length; i++) { for (j = 0; j < amandasPets.length; j++ ) { if ( johnsPets[i] === amandasPets[j] ) { petsInCommon.push(johnsPets[i]);} } } console.log(petsInCommon );

13th Feb 2021, 8:12 AM
SuperKitsune94
SuperKitsune94 - avatar
3 Answers
+ 2
Because johnsPets.length is 4 and last index in array is 3!
13th Feb 2021, 8:15 AM
Abhay
Abhay - avatar
+ 2
the variable i used here for indexing... so it has to be in the range of the array.... and the range of the array is 0 to its length-1 including. hence we can say the variable should be less than the length of the list.
13th Feb 2021, 8:54 AM
NaSaPaKri
NaSaPaKri - avatar
+ 1
Abhay NaSaPaKri Thank you both! So it has to do with the zero indexing of the array.
13th Feb 2021, 9:21 AM
SuperKitsune94
SuperKitsune94 - avatar