Wasbeer
Wasbeer

Reputation: 389

In variadic JavaScript functions, when would one use the arguments object instead of rest parameters?

The arguments object behaves as follows:

function myFunc1(a, b, c) {
  console.log(arguments[0]);
  // expected output: 3

  console.log(arguments[1]);
  // expected output: 2

  console.log(arguments[2]);
  // expected output: 1

  console.log(arguments.sort());
  // expected output: "VM427:11 Uncaught TypeError: arguments.sort is not a function"
}

myFunc1(3, 2, 1);

Rest parameters behave as follows:

function myFunc2(...args) {
    console.log(args[0]);
  // expected output: 3

  console.log(args[1]);
  // expected output: 2

  console.log(args[2]);
  // expected output: 1

  console.log(args.sort());
  // expected output: [1, 2, 3]
}

myFunc2(3, 2, 1)

Rest parameters enable the passing of arguments as an actual array, including its prototype methods, rather than the arguments pseudo-array, without them.

Except for compatibility reasons (rest parameters were introduced in ES6), are there cases wherein one would use the arguments object instead of rest parameters?

Upvotes: 0

Views: 212

Answers (1)

t.niese
t.niese

Reputation: 40842

The only thing that comes to my mind is if you have something like this as the signature function myFunc2(a1, a2, ...args) and you want to pass all arguments to another function:

function myFunc2(a1, a2, ...args) {
   // so something based on a1, a2 or args

   // pass all arguments to another function
   anotherFunc(...arguments);
}

You for sure could write: anotherFunc(a1, a2, ...args);, but maybe anotherFunc(...arguments) expresses more that you are forwarding all arguments of myFunc2

Upvotes: 1

Related Questions