How to handle calling functions on data that may be undefined?

Check the array before using map:

arr && arr.map()

OR,

arr && arr.length && arr.map() // if you want to map only if not empty array

OR,

We can even use like this (as commented by devserkan):

(arr || []).map()

As per your comment:

I wish there was a safe navigation operator like with C# (arr?.map())

Yes, obviously. This is called optional chaining in JavaScript which is still in proposal. If it is accepted, then you may use like this:

arr?.map()

You can see it in staging 1 for which you may use babel preset stage1


But obviously, except the checking array length, your requirement will not be fulfilled:

This results in an error because, of course, the first index of the array is undefined.

So, I suggest you to use:

arr && arr.length && arr.map()

Leave a Comment