All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.javascript.rules.javascript.S930.html Maven / Gradle / Ivy

There is a newer version: 10.17.0.28100
Show newest version

Why is this an issue?

When you call a function in JavaScript and provide more arguments than the function expects, the extra arguments are simply ignored by the function.

function sum(a, b) {
  return a + b;
}

sum(1, 2, 3); // Noncompliant: The last argument is unexpected and will be ignored

Passing extra arguments in JavaScript is not inherently "bad," but it can lead to some potential issues or confusion if not handled correctly:

  • The function signature is an essential part of its interface. Passing extra arguments can obscure the function’s intended use and make it less clear what the function actually requires.
  • This can lead to unexpected behavior, as the function might not work as intended or produce incorrect results.
  • Code that passes extra arguments can become harder to understand and maintain, especially when revisiting it at a later time.
  • Other developers might find it challenging to comprehend the function’s purpose if extra arguments are scattered throughout the codebase.
  • If you refactor the function later or rely on an external library that changes the expected number of arguments, your code with extra arguments could break unexpectedly.

While it’s possible to pass extra arguments, it’s essential to note that accessing those extra arguments directly inside the function is not straightforward. One common approach to handling extra arguments is to use the arguments object, which is an array-like object available within all function scopes.

function sum() {
  let total = 0;
  for (let i = 0; i < arguments.length; i++) {
    total += arguments[i];
  }
  return total;
}

sum(1, 2, 3); // Compliant

However, it’s generally recommended to use the rest parameter syntax (...args) or utilize other techniques like the spread operator to deal with variable numbers of arguments in a more readable and maintainable way.

function sum(...args) {
  return args.reduce((a,b) => a + b, 0);
}

sum(1, 2, 3); // Compliant

Exceptions

No issue is reported when arguments is used in the body of the function being called.

function doSomething(a, b) {
  compute(arguments);
}

doSomething(1, 2, 3); // Compliant

Resources

Documentation





© 2015 - 2024 Weber Informatics LLC | Privacy Policy