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

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

    I think it is very debatable what to use. I prefer code that is semantically as accurate as possible, so I think undefined is appropriate in this case.

    I think of null assignments as meaning "a variable set to nothing". This is as opposed to undefined meaning "this thing isn't there at all"

    As a previous answer pointed out, returning undefined has issues, and it's completely up to you whether that bothers you. It wouldn't bother me.

    0 讨论(0)
  • 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 <string[],boolean[]>  
    ['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

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-07 11:41

    Here's an example where undefined makes more sense than null:

    I use a wrapper function for JSON.parse that converts its exception to undefined:

    // parses s as JSON if possible and returns undefined otherwise
    // return undefined iff s is not a string or not parseable as JSON; undefined is not a valid JSON value https://stackoverflow.com/a/14946821/524504
    function JSON_parse_or_undefined(s) {
        if ("string" !== typeof s) return undefined
    
        try {
            const p = JSON.parse(s)
            return p
        } catch (x){}
    
        return undefined
    }
    

    Note that null is valid in JSON while undefined is not.

    0 讨论(0)
  • 2020-12-07 11:42

    First answer is right. They have theoretically different meaning. However it's not always clear which to pick up.

    I tend to use null in my development although I think that's completely subjective thing.

    I use that mostly because:

    1. undefined variable might be overwritten in old browsers so returning it is a little bit more complicated. This same issue forces you to use typeof var === 'undefined' when getting function results. link

    2. Other languages tend to use null widely, a lot of them don't even have undefined (php for example). That gives me kind of consistency when quickly swapping between languages.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题