I wanted to have an optional boolean
parameter to a function call:
function test() {
if (typeof(arguments[0]) === 'boolean') {
// do some stuff
}
// rest of function
}
I want the rest of the function to only see the arguments
array without the optional boolean
parameter. First thing I realized is the arguments
array isn't an array! It seems to be a standard Object
with properties of 0, 1, 2, etc. So I couldn't do:
function test() {
if (typeof(arguments[0]) === 'boolean') {
var optionalParameter = arguments.shift();
I get an error that shift()
doesn't exist. So is there an easy way to remove an argument from the beginning of an arguments
object?
arguments
is not an array, it is an array like object. You can call the array function inarguments
by accessing theArray.prototype
and then invoke it by passing theargument
as its execution context using.apply()
Try
Demo
another version I've seen in some places is
Demo
It's not fancy but the best solution to remove the first argument without side effect (without ending with an additional argument as would do
shift
) would probably beExample :
As Arun pointed out
arguments
is not an arrayYou will have to convert in into an array
var optionalParameter = [].shift.apply(arguments);