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

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

    I will argue there is no best way, and even standard functions sometimes choose one or the other.

    For example:

    • [[Prototype]]

      Ordinary objects have a [[Prototype]] internal slot, which determines from which other object they inherit from. Of course, there must be a way to say that an object does not inherit from any other one. In this case, "there is no such object" is represented using null.

    • Object.getOwnPropertyDescriptor

      It is expected to return a property descriptor, that is, an object which describes a property (e.g. value, writability, enumerability and configurability). However, the property may not exist. In this case, "there is no such property" is represented using undefined.

    • document.getElementById

      It is expected to return the element with the given ID. However, there might be no element with that ID. In this case, "there is no such element" is represented using null.

    So just choose whatever you prefer or think makes more sense for your specific case.

提交回复
热议问题