Array methods should not be called on the arguments object itself

  • BAD_ARRAY_METHOD_ON_ARGUMENTS
  • Error
  • High
  • No tags

This rule applies when an array method is called on the arguments object itself.

The arguments object is not an array, but an array-like object. It should be converted to a real array before calling an array method. Otherwise, a TypeError exception will be thrown because of the non-existent method.

You can consider using Array.prototype.slice() or ES6 rest parameters to convert the arguments object to a real Array object.

Noncompliant Code Example

View with compliant examples side by side
function add(x, y) {
    return x + y;
}
function sum() {
    return arguments.reduce(add, 0); // BAD_ARRAY_METHOD_ON_ARGUMENTS alarm because 'reduce()' is an array method.
}

Compliant Code Example

View with noncompliant examples side by side
function add(x, y) {
    return x + y;
}
// Replace 'arguments' with ES6 rest parameter, which is a real array.
function sum(...args) {
    return args.reduce(add, 0);
}
// Or when ES6 is not available, convert 'arguments' to an array.
function sum() {
    var arr = Array.prototype.slice.call(arguments);
    return arr.reduce(add, 0);
}

Version

This rule was introduced in DeepScan 1.32.0.

See

Was this documentation helpful?