is there a difference accessing javascript arguments via the default ‘arguments’ and using an explicit object such as ‘options’?
are these two similar apart from that one accesses the array arguments and the other accesses the object options?
$.fn.myFn = function(){
if arguments[0]//....
}
and
$.fn.myFn = function(options){
if options.value //....
}
Yes, they’re similar, but they’re different as well. I wouldn’t use
argumentsfor anything that doesn’t truly need to handle variable numbers of arguments; I’d use declared arguments and/or anoptionsobject. (Also note that on most JavaScript engines, using theargumentspseudo-array [it’s not really an array] incurs a runtime speed penalty compared with using declared arguments, or even anoptionsobject. 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.:
If
parseIntused anoptions-style object, you’d have to write that as:…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
optionspattern where you pass in an object instead of discrete arguments can have real payoffs. Consider the jQueryajaxfunction. It has ~32 options you can pass to it, nearly all of them optional. Just as you probably wouldn’t want to code everyparseIntas above, you probably wouldn’t want to code everyajaxcall like this:…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
argumentsbeing 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
argumentsto passing in an array, for those times you really need a variable number of arguments (answer: you’re better off with the array).