Drop It Challenge Empty Array Issue

The code below passes all tests except for the one that is provided to the function in this instance below. When I log result to the console it shows an empty array which is what the question is asking for. I am not sure why this doesn’t pass the test. What am I missing? Thanks!

function dropElements(arr, func) {
  const result = [];
  arr.forEach((item, index) => {
    if(func(item)){
      result.push(index);
    }
  });
  
  if(result === []) {
    return result;
  } else {
    return arr.slice(result[0]);
  }
  
}

dropElements([1, 2, 3, 4], function(n) {return n > 5;});

This doesn’t mean what you think it means.

In JS there are two kinds of data types, primitives and reference types.

The primitive types are: string, number, bigint, boolean, symbol, null, and undefined. For those variable types, JS stores the actual value in the variable. So, that type of comparison above makes sense.

In JS, all other data types are reference types, meaning that the variable stores a “reference” or “memory address”. These include objects, arrays, functions, etc. (And it’s worth pointing out that in JS, all reference types are technically objects under the covers.)

So, you JS evaluates something like result === [], what it is being asked is, “Is the memory address stored in result the same as the memory address for the anonymous empty array literal we’ve temporarily created.” (That will always be false.)

Does that make sense?

There are times when you want to make comparisons like you have above, but it is to see if one array/object/whatever is the exact same place in memory, not that they are “equal”. For that matter, determining equality reference types can be complicated and (unless the object or array is very simple) it may need to be implemented on a case by case basis.

In any case, you are trying to figure out if the array is empty. You can just check the length for that.

Incidentally, remember this discussion about reference types and memory addresses - that will come up a few more types in JS, with some more “gotchas”.

1 Like

Absolute champion of an answer! That makes total sense now. Fixed, passed, and on to the next one. I will definitely keep this discussion in mind for future ‘gotchas’. Thanks!

1 Like

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