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 );
3 Answers
+ 2
Because johnsPets.length is 4 and last index in array is 3!
+ 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.