Yes, they're similar, but they're different as well. I wouldn't use arguments
for anything that doesn't truly need to handle variable numbers of arguments; I'd use declared arguments and/or an options
object. (Also note that on most JavaScript engines, using the arguments
pseudo-array [it's not really an array] incurs a runtime speed penalty compared with using declared arguments, or even an options
object. See "side note" below, though of course you have to call the function a lot for that overhead to matter in the real world.)
Using declared arguments for functions that accept only a couple of arguments usually makes sense, e.g.:
x = parseInt(str, 10);
If parseInt
used an options
-style object, you'd have to write that as:
x = parseInt({string: str, radix: 10}); // Note: parseInt doesn't actually work this way
...or similar, which is more typing on every call. So that's a downside.
But when you get into lots of arguments, and particularly lots of optional arguments, using the options
pattern where you pass in an object instead of discrete arguments can have real payoffs. Consider the jQuery ajax
function. It has ~32 options you can pass to it, nearly all of them optional. Just as you probably wouldn't want to code every parseInt
as above, you probably wouldn't want to code every ajax
call like this:
$.ajax(
"/path/to/resource",
function(data) {
},
undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined,
undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined,
undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined,
undefined, undefined, undefined, undefined, undefined, undefined
);
...either. :-)
One rule of thumb I've heard for discrete arguments vs. options
-style objects is when you get to four arguments, people are going to start getting lost. You'll want to draw your own line, of course.
Side note: More about arguments
being slower than declared args, try this test. Now of course, call overhead doesn't matter most of the time, so most of the time this doesn't matter. But for those times it does, here are the results from me and others:

As you can see, using declared arguments is the fastest by far on pretty much all engines. I even threw in something comparing arguments
to passing in an array, for those times you really need a variable number of arguments (answer: you're better off with the array).