Value won't print

This is the solution. But according to this solution, in the first if statement, the second or condition translates to obj[first] in the first example which translate to the value of the first property. But when I try let person = { first: "Romeo", last: "Montague" }; console.log(person[first]); in a code editor I get an error.

function whatIsInAName(collection, source) {
  // "What's in a name? that which we call a rose
  // By any other name would smell as sweet.”
  // -- by William Shakespeare, Romeo and Juliet
  var srcKeys = Object.keys(source);

  // filter the collection
  return collection.filter(function(obj) {
    for (var i = 0; i < srcKeys.length; i++) {
      if (
        !obj.hasOwnProperty(srcKeys[i]) ||
        obj[srcKeys[i]] !== source[srcKeys[i]]
      ) {
        return false;
      }
    }
    return true;
  });
}

This tells Javascript to access the property of person with the string stored in the variable first

Right so it should print out β€œRomeo” correct?

no, because first is not a string, it is a variable name that has yet to be defined.

To access the first property of the object person, person['first'] would be correct.

1 Like

Ah so the reason this works in the solution is because the .keys() method is storing an array of strings. So obj[srcKeys[i]] equates to obj["first"] in the first example right?

2 Likes

Exactly right. srcKeys is an array of string values, each string being one of three property names on the src object. srcKeys[0] is one of those property names, might be "first" or might not. There is no hard rule about how property names get ordered when pulled by Object.keys()

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