4

In playing with jQuery's utility method, jQuery.map(), I noticed that an undefined return value is omitted from the returned array. What is the reason for this?

var letters = ['a', undefined, 'c', undefined, 'e'];
console.log(letters); //["a", undefined, "c", undefined, "e"] 
console.log(letters.length); //5 

var lettersMapped = $.map(letters, function(item, index){
    var item = item;
    return item;
});

console.log(lettersMapped); //["a", "c", "e"]
console.log(lettersMapped.length); //3
2
  • 1
    Maybe the documentation has an answer? The function can return: [...] null or undefined, to remove the item Commented May 13, 2014 at 23:27
  • @Jon please see my comment below regarding the documentation. Commented May 14, 2014 at 0:25

1 Answer 1

2

Per the documentation for jQuery.map:

The function can return:

  • the translated value, which will be mapped to the resulting array
  • null or undefined, to remove the item
  • an array of values, which will be flattened into the full array

In other words, this is the expected behaviour of jQuery.map.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks but I had already read the documentation. Clearly, this is intended behavior. My question is why is that the intended behavior, as this could yield unintended results. For instance, what if I want the item to be undefined?
@maxhallinan: Although that part's consequences are not as immediately clear, you can also return an array of values, which will be flattened into the full array. So: return item === undefined ? [undefined] : item. Same for null. In any case, your original question was perfectly answered by "read the docs". And why this is the chosen behavior can only be definitively answered by a couple of people on the planet -- the ones who designed it.
@Jon Fair enough. I meant why as in "is there an obvious good reason for this that I'm missing." Very much like your workaround. Please post this comment as an answer so I can accept.
@maxhallinan: I don't think copy/pasting the above into another answer would offer anything. Feel free to accept this one instead.
@Jon Thanks for the tip -- you can always return [null] or [undefined]. @maxhallian It's an easy way to remove elements from the array. Say, for instance, I have an array of numbers and I want to filter only the positive ones: var numbers = $.map([-3, 5, -2, 6, 8], function (n) { return n > 0 ? n : undefined; });. That's a little more concise (IMHO) than var numbers = []; $.each([-3, 5, -2, 6, 8], function (i, n) { if (n > 0) { numbers.push(n); } });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.