Skip to content

Instantly share code, notes, and snippets.

@rkatic
Created April 30, 2011 07:00
Show Gist options
  • Save rkatic/949493 to your computer and use it in GitHub Desktop.
Save rkatic/949493 to your computer and use it in GitHub Desktop.
isArguments
// Cross-browser but not absolutely strong.
function isArguments( obj ) {
return typeof obj === "object" && ( "callee" in obj ) && typeof obj.length === "number";
}
// Ideally strong, but broken on Opera...
var isArguments = (function( undefined ) {
var toStr = ({}).toString,
returnTrue = function() {
// To be sure it will not be inlined (future engines).
return arguments !== undefined;
},
test = function( obj ) {
return obj != null && toStr.call( obj ) === "[object Arguments]";
};
return test( arguments ) ? test :
function( obj ) {
// Using "in" works in strict mode too.
if ( obj != null && "callee" in obj ) {
try {
return returnTrue.apply( this, obj );
} catch (e) {}
}
return false;
};
})();
@kflorence
Copy link

Very smart using .apply as a final test for object as array! My only question is why the "undefined" argument to the first function?

@rkatic
Copy link
Author

rkatic commented May 2, 2011

For three reasons:

  1. The global undefined can be redefined. It's just a variable as another.
  2. It's bit faster because one scope closer to the usage scope.
  3. Minifiing, "undefined" becomes only one letter long.

@kflorence
Copy link

Oh yes, I understand that. I thought it had some other relevance to the function.

What are the benefits of the closure and extra function calls? Isn't this basically the same:

var isArguments = function(obj) {
    var cls = Object.prototype.toString.call(obj);

    if (cls == "[object Arguments]") {
        return true;
    } else if (obj != null && "callee" in obj) {
        try {
            return (function() {
                return arguments !== undefined;
            }).apply(this, obj);
        } catch (e) {}
    }

    return false;
};

@rkatic
Copy link
Author

rkatic commented May 2, 2011

Yes, it's basically the same. Just slower, mainly because of the function definition on every run..

@kflorence
Copy link

Makes sense. Nice work!

@rkatic
Copy link
Author

rkatic commented May 2, 2011

Just note that your versions will fail with null or undefined values, so you should do obj != null as first check.

@kflorence
Copy link

Yeah I forgot to put that in there on my initial post, but I added it in right afterwards. Doh!

https://gist.github.com/952521

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment