Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should search method return if nothing found?

Tags:

javascript

I have this method

var link = this.find_first_link(selectedElem);

which should return an object. I'm not sure what should it return if no element is found - null, undefined or false? I've rejected 'false' option since I don't think it suits here so I'm choosing betwen null or undefined. I've read that 'undefined' should be used where some kind of exception or error occurs, so currently this method returns null. Is that OK?

like image 901
Max Koretskyi Avatar asked Oct 17 '13 06:10

Max Koretskyi


1 Answers

Look at what is done in methods you have in your browser.

getElementById returns null when there is no element with the id provided.

That's what null has been designed for : to represent the absence of an object (typeof null is "object"). Use it when the expected returned type is "object" but you have no object to return. It's better than undefined here because you would have undefined before you even decided what to put in the variable or before you even call the function.

From the description of null in the MDN :

In APIs, null is often retrieved in place where an object can be expected but no object is relevant.

Yes, use null.

like image 67
Denys Séguret Avatar answered Sep 23 '22 23:09

Denys Séguret