Is it better to return `undefined` or `null` from a javascript function?

前端 未结 10 1304
暖寄归人
暖寄归人 2020-12-07 10:58

I have a function which I have written which basically looks like this:

function getNextCard(searchTerms) {
  // Setup Some Variables

  // Do a bunch of log         


        
10条回答
  •  悲哀的现实
    2020-12-07 11:32

    My personal opinion according to my experience is don't use undefined and null if you don't want to crash your code. At least I would avoid it personally. There is a lot of functions in Javascript that return undefined and ok we must to use to it. But when you design your code don't use it. It is important to always return something "false" at least. If you have an array for example and you map over it. It is not good to return [undefined, undefined.....] or just undefined. Is better if you keep the type of the original array. Example:

     const mapper:Map   
    ['i', 'dont', 'use', 'null or undefined'] -> [false, true, false, true, false]
    or ['', dont, '', '', use] 
    or al the stuff above and then filter(v => v)
    that will keep all undefined and null out
    

    That's the idea. I try all the time to avoid it. Because a null or undefined can easily crash your code

提交回复
热议问题