1

The code just returns what is in the first argument that matches the second argument and it checks out. link just in case

My main focus is "source[srcKeys[i]]" in the if statement. "srcKeys" alone returns "['last']" but if you add 'source' in front of it such as "source[srcKeys]" you get "Capulet". My question is why its returning "Capulet" and not "['last']" since it targets the Object.keys and not the value?

    function whatIsInAName(collection, source) {
  var srcKeys = Object.keys(source);



  return collection.filter((obj) => {

    for (var i = 0; i < srcKeys.length; i++) {
      if (obj[srcKeys[i]] !== source[srcKeys[i]]) {
        return false
      }
    }
    return true;
  });
}

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

1 Answers1

0

but if you add 'source' in front of it such as "source[srcKeys]" you get "Capulet"

Did you actually try this?

It sounds like what you are saying is that the expression source[['last']] would evaluate to Capulet.

Let's try it:

const collection = [{
    first: "Romeo",
    last: "Montague"
  },
  {
    first: "Mercutio",
    last: null
  },
  {
    first: "Tybalt",
    last: "Capulet"
  }
];

const source = {
  last: "Capulet"
};

const srcKeys = Object.keys(source);

console.log(source[srcKeys]);

Well I'll be...another Javascript gem! Wonderful!

Here be dragons

Ok so it looks like JavaScript allows you to index into an array using an single element array as the index and it will just work.

The only thing I was able to find on the internet explaining this, is this blog post.

The post also goes on to show that even doing something like:

source[[[[srcKeys]]]]

Will also give the result Capulet.

How wonderful!

Moral of the story is: Javascript has a lot of quirks that are not immediately obvious. I would call them undefined, but Javascript seems pretty consistent in the quirky department. This is why many developers turn to other languages that compile down to Javascript simply to avoid these hidden gotchas.


My question is why its returning "Capulet" and not "['last']"

Well in this case, it will not should not return/evaluate to ['last'] unless you have a value in source which is a list containing just 'last'. Who knows, maybe there exists another hidden quirk of JavaScript that just might return ['last']. As far as I know, it should not be possible, but I've been wrong before...

smac89
  • 39,374
  • 15
  • 132
  • 179