Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing an argument from arguments in JavaScript

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?

like image 310
at. Avatar asked Nov 11 '13 10:11

at.


People also ask

How do you remove an argument from an array?

Using the Array. splice() method accepts three arguments: start , delete , and items . The first, start , is the index of the item you want to modify in the array. It's the only required argument. The second, delete , is the number of items to delete from the array.

What is passing argument in JavaScript?

Arguments are Passed by Value The parameters, in a function call, are the function's arguments. JavaScript arguments are passed by value: The function only gets to know the values, not the argument's locations. If a function changes an argument's value, it does not change the parameter's original value.


2 Answers

arguments is not an array, it is an array like object. You can call the array function in arguments by accessing the Array.prototype and then invoke it by passing the argument as its execution context using .apply()

Try

var optionalParameter = Array.prototype.shift.apply(arguments);

Demo

function test() {
    var optionalParameter;
    if (typeof (arguments[0]) === 'boolean') {
        optionalParameter = Array.prototype.shift.apply(arguments);
    }
    console.log(optionalParameter, arguments)
}
test(1, 2, 3);
test(false, 1, 2, 3);

another version I've seen in some places is

var optionalParameter = [].shift.apply(arguments);

Demo

function test() {
    var optionalParameter;
    if (typeof (arguments[0]) === 'boolean') {
        optionalParameter = [].shift.apply(arguments);
    }
    console.log(optionalParameter, arguments)
}
test(1, 2, 3);
test(false, 1, 2, 3);
like image 82
Arun P Johny Avatar answered Oct 30 '22 23:10

Arun P Johny


As Arun pointed out arguments is not an array

You will have to convert in into an array

var optionalParameter = [].shift.apply(arguments);

like image 39
Clyde Lobo Avatar answered Oct 30 '22 23:10

Clyde Lobo