Why will not he pass the test that he should & ldquo; return an empty array if the property does not exist & rdquo;

advertisements

The problem:

Given an object and a key, "getEvenElementsAtProperty" returns an array containing all the even elements of the array located at the given key.

Notes:

  • If the array is empty, it should return an empty array.
  • If the array contains no even elements, it should return an empty array.
  • If the property at the given key is not an array, it should return an empty array.
  • If there is no property at the given key, it should return an empty array.

My Code:

 var obj = {
 key: [1000, 11, 50, 17]
 }; // sample object

    function getEvenElementsAtProperty(obj, key) {
      var arr = []
      if (!obj[key]) arr = []
      if (!obj[key] % 2=== 0) arr = []
      for (var i = 0; i < obj[key].length; i++){
          if (obj[key][i] % 2 === 0) arr.push(obj[key][i])
      }
      return arr;
      }
    getEvenElementsAtProperty(obj, 'key') // [1000, 50], yet still doesn't pass

Question:

Why do I still get the error saying that it doesn't return an empty array if the property doesn't exist? I thought this is done by line 3: if (!obj[key]) arr = [], if I comment this out the function still returns the same thing. What is going on with this and how do I return an empty array if the property does not exist.


You initialize arr to an empty array, then conditionally do the same thing twice more. It should be clear that those conditions cannot ever change the behavior of the function, so they can be removed without changing the behavior of the function at all.

If removed, next thing you know obj[key].length is evaluated in order to start the loop. But what if obj[key] doesn't have a length? Error occurs.

What you should be doing is immediately return [] if any of the necessary conditions for the loop to work does not hold. By the way, those conditions are #3 and #4; a properly written loop will take care of #1 and #2 "for free".