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

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

提交回复
热议问题