tags:

views:

67

answers:

3

Hi,

Lets say we have a function of the form:

function getReferenceToFoo( idName )
{
    if( ! document.getElementById( idName ) )
    {
        return;
    }
    ... 
    // else return reference to element normally
}

What is the best way to indicate failure by return type? By my mind I could do one of the following:

  1. Just 'Return' (as above)
  2. Return 'null'
  3. Return 'undefined'

Which is the best practice and why?

A: 

Return false or nothing. Just return will act as null if you're doing:

foo = getReferenceToFoo('myID');
if (foo) {
    // do things
}
Oli
Just `return` will actually act as `undefined`, not `null`. And we all know there is a difference (vague but never the less it´s there).
anddoutoi
A: 

If you want to return something, I'd return null, because the very purpose of null is to indicate, well, a null content.

Wikipedia for Null:

Null is a special pointer value (or other kind of object reference) used to signify that a pointer intentionally does not point to (or refer to) an object.

Else if you'd like precision or interruption on failure, you may want to throw an exception.

streetpc
+2  A: 

In JavaScript all functions return, even if you don´t explicitly make them return. If there are no return statement a function will return undefined. There is however one exception to this. If you use the new statement the function will return an instance of this.

So:

function doFoo()
{
    // do nothing
}

,

function doFoo()
{
    return;
}

and

function doFoo()
{
    return undefined;
}

are all the same to the JavaScript engine.

I really can´t recommend using null as return value in JavaScript. null is an object and doing type checking can lead to weird logic. If you use null as return you better change the expression in the if() to be more explicit.

foo = getReferenceToFoo('myID');
// foo might be a reference or null
if (null !== foo) {
    // do things
}

EDIT: changed from the not equality operator (!=) to the strict not equality (!==).

But honestly I don´t know why you are doing this. The method document.getElementById returns null if it can´t find anything.

I know this is a antipattern but I actually do use:

var myElmnt;
if ((myElmnt = document.getElementById('myId')))
{
    // do stuff with myElmnt
}

Yeah, I know, I will burn in hell and all.

anddoutoi
Great answer (+1). I actually rather like the [if ((myElmnt = document.getElementById('myId'))) {..} ] 'antipattern' as you put it. Why is it an antipatten though?
Konrad
I read it in some book and I think the argument was that only comparison operators should be allowed as expressions at this place. This way you more easily find errors when scanning code and it is actually subject for more errors. You could easily slip an extra `=` and JavaScript would swallow it w/o giving you any feedback why your application don´t behave as expected. But as with all things: if you know what you are doing...
anddoutoi