This page looks best with JavaScript enabled

Don't use arguments object in Arrow functions

 ·   ·  ☕ 1 min read

Arguments object throws an error when used with arrow functions.

Consider this code -

1
2
3
4
5
6
function getSum() {
  return arguments[0] + arguments[1];
}

console.log(getSum(1, 2));
// 3

The result is as expected. But, you cannot do the same using an arrow function.

1
2
3
4
5
6
const getSum = () => {
  return arguments[0] + arguments[1];
};

console.log(getSum(1, 2));
// gobbledygook or error

You will see a function definition, or an error depending on the runtime engine. Arrow functions do not provide the binding for arguments object like regular functions.

Just use a rest operator instead of arguments, and it works in both normal and arrow functions.

1
2
3
4
5
6
const getSum = (...args) => {
  return args[0] + args[1];
};

console.log(getSum(1, 2));
// 3
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things