Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
-2
rated 0 times [  1] [ 3]  / answers: 1 / hits: 120902  / 8 Years ago, thu, june 23, 2016, 12:00:00

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



function getNextCard(searchTerms) {
// Setup Some Variables

// Do a bunch of logic to pick the next card based on termed passed through what I'll call here as 'searchTerms' all of this logic is omitted because it's not important for my question.
// ...

// If we find a next card to give, than give it
if (nextCardFound)
return nextCardFound;

// Otherwise - I'm returning undefined
return undefined;
}


Question: Would it be better to return null here?



I can pass whatever I want back - obviously... I just wasn't sure what is the best thing to use.



The code that calls this function knows how to deal with undefined (it actually won't ever really happen unless something goes horribly wrong)



The reason I'm asking this question is that I heard somewhere something that sounded like Don't assign undefined to variables or something - that it will make it harder to debug. So, the fact that I can see that null gets passed back tells me that the return is working - but basically function similar to undefined.






Documentation:



Mozilla Docs Didn't answer my question... google didn't either :



This SO Question - was way too broad for what I'm trying to figure out here.


More From » function

 Answers
3

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.


[#61680] Monday, June 20, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
clarkulisesa

Total Points: 422
Total Questions: 93
Total Answers: 112

Location: Austria
Member since Thu, Jan 7, 2021
3 Years ago
clarkulisesa questions
Mon, Feb 24, 20, 00:00, 4 Years ago
Mon, Aug 12, 19, 00:00, 5 Years ago
;