Infinite loop in code

Tell us what’s happening:
Describe your issue in detail here.
Hello. Could someone help me out with why this code is returning an infinite loop

  **Your code so far**

function whatIsInAName(collection, source) {
const arr = [];
// Only change code below this line
const allKeys = Object.keys(source);
for(let i = 0; i < collection.length; i++){for(let j = 0; allKeys.length; j++)
{if(collection[i].hasOwnProperty(allKeys[j]) || collection[allKeys[j]] === source[allKeys[j]]){arr.push(collection[i]);}}}

// Only change code above this line
return arr;

console.log(whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" }));
  **Your browser information:**

User Agent is: Mozilla/5.0 (iPhone; CPU iPhone OS 15_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1

Challenge: Wherefore art thou

Link to the challenge:

Hey there :wave: :slightly_smiling_face:

Remember the middle statement in a for loop is the one that decides if the loop will continue, right?
Here you have allKeys.length as the condition, but I don’t see the length of allKeys getting changed in the loop. Meaning if you enter the loop with allKeys.length > 0 it will always be true.

How to fix it though? :thinking:
You could modify the length of allKeys but I don’t think that’s necessary. Why not compare j and allKeys.length?

Ohh yes thank you. I hadn’t seen that
Will just compare j with allKeys length

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.