This page looks best with JavaScript enabled

Arguments Object in Javascript

 ·   ·  ☕ 2 min read

Arguments object enables you to treat function arguments with respect.. and the developers with compassion.

How do you pass arguments to a function?

In its most primitive form:

1
2
3
function getSum(a, b) {
  return a + b;
}

This is perfectly ok in an ideal world where Buddha walks the earth.

In the real world populated by Agent Smith and his compadres, one has to be more defensive with function arguments. One of the ways of doing that is by using arguments.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function getSum(a, b) {
  console.log("arguments: ", arguments);
  // [Arguments] { '0': 2, '1': 3 }

  let sum = 0;
  for (arg in arguments) sum += arguments[arg];
  return sum;
}

console.log("getSum: ", getSum(2, 3)); // 5
console.log("getSum: ", getSum(2, 3, 1)); // 6

Where should you use arguments?

The alternative, and probably a more common pattern, is to use the rest operator or assignment destructuring against a single object passed as argument. This can be considered the next gen function and should replace the older arguments object.

1
2
3
function getSum({ ...nums }) {
  return [nums["x"] + nums["y"]];
}

My preferred approach..

1
2
3
4
5
6
7
8
9
function getSum(nums) {
  let { x, y } = nums;
  // OR let { x, y } = {...nums};

  return x + y;
}

console.log("getSum: ", getSum({ x: 2, y: 3 })); // 5
console.log("getSum: ", getSum({ x: 2, y: 3, z: 1 })); // 5
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things