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

前端 未结 10 1267
暖寄归人
暖寄归人 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:44

    I will give you my personal opinionated way of choosing between the two.

    My simple question is: could the value, given another input/state/context be defined to something?

    If the answer is yes then use null else use undefined. More generally any function returning an object should return null when the intended object does not exist. Because it could exist given another input/state/context.

    null represents the absence of value for a given input/state/context. It implicitly means that the concept of the value itself exist in the context of your application but may be absent. In your example the concept of a next card exists but the card itself may not exist. null should be used.

    undefined implicitly represents the absence of meaning of that value in your application's context. For example, if I manipulate a user object with a given set of properties and I try to access the property pikatchu. The value of this property should be set to undefined because in my context it doesn't make any sense to have such a property.

提交回复
热议问题