Wherefore art thou logic

function whatIsInAName(collection, source) {
  // What's in a name?
  var arr = [];
 
    arr = collection.filter(function(elem) {
    
    for (var i in source); {
   if (source[i] != elem[i]) {
  
   return false; 


}
   }
return true; 

}); 
  

return arr;
}

whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });

[{ first: “Tybalt”, last: “Capulet” }]. <<< This is the output

First of all, the if statement checks,
if (source[i] != elem[i])
if capulet != elem[i])
the capulet IS NOT equal to any value in source array, and since the first object is already FALSE, the for loop should stop executing. How did it manage to return [{ first: “Tybalt”, last: “Capulet” }] … Arent we checking for FALSE? The first one is already FALSE so it should return [{ first: “Romeo”, last: “Montague” }]

There’s a few things going on here.
Firstly, you are treating source as an array when you do source[i]. But source is an object.
Secondly, you cannot directly compare objects for equality. Using ==, !=, on objects doesn’t check whether their properties are the same, but whether they are actually the same object (referencing the same place in memory). In order to check whether two different objects are equal, you need to look at their properties directly.

2 Likes