Wherefore art thou Solution 1 redundant?

Tell us what’s happening:

i just solved the challenge (with a complete different and more “complex” and confusing code). Now i want to understand at least solution 1, to learn to be a “cleaner” coder.

I was a bit confused why is the the first condition in the if statement:


Because i was thinking, the second condition is also checking of obj has the property of srcKeys[i]. After i deleted it, the challenge was also solved. So my guess was correct. But know i am thinking: There must be a reason for the first if-condition. Why ?

I thought maybe for Performance-issues. But this is not correct, because it will first check the first condition and if its wrong, it will then check for the second condition anyway.

Can someone explain me the reason for the first-condition? What is the use case?

  **Your code so far**

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;

  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:95.0) Gecko/20100101 Firefox/95.0

Challenge: Wherefore art thou

Link to the challenge:

Someone may have to correct me here. I believe the first if condition is checking if the property doesnt exist. The second condition is checking if the two values are not the same.

Not quite. It just looks at the value of obj[srcKeys[i]]. If that property doesn’t exist on obj, then obj[srcKeys[i]] would be undefined.

!obj.hasOwnProperty(srcKeys[i]) || obj[srcKeys[i]] !== source[srcKeys[i]]

This translates to "if the object does not have that property, or if the value of that property is different from the one in source". Not truly redundant because those are two different things.

Now, what we can do is leverage out knowledge of the context to simplify that statement a little bit. Because srcKeys are the properties of source, we know that source[srcKeys[i]] will not be undefined. In that way, we can rely on obj[srcKeys[i]] !== source[srcKeys[i]] to be true for any property that is not present in obj. We can tidy up the if statement based on the context that we have.

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