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

后端 未结 2 473
情书的邮戳
情书的邮戳 2020-11-28 16:02

I primarily work with React and often find that when I write a function that relies on a component\'s state, I have to perform a check to see if the piece of state is define

2条回答
  •  借酒劲吻你
    2020-11-28 16:45

    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()
    

提交回复
热议问题