开发者

Best way to return early from a javascript function normally returning a reference

Lets say we have a function of the form:

function getReferenceToFoo( idName )
{
    if( ! document.getElementById( idName ) )
    {
        return;
    }
    ... 
    // e开发者_开发技巧lse 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?


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.

I would recommend to only return null as a failing value from functions where expected return value is some kind of object. If expected return value is some kind of primitive I would consider undefined.

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

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.


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.


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

foo = getReferenceToFoo('myID');
if (foo) {
    // do things
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜