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

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

There is a newer version: 5.0.0.6962
Show newest version

Why is this an issue?

JavaScript has the new keyword that is used in conjunction with constructor functions to create new instances of objects. When you use the new keyword with a function, it signifies that the function is intended to be used as a constructor function to create objects.

Any function can be used as a constructor function by convention. Constructor functions are used to create new objects with the same structure or properties. They are typically named with an initial capital letter to distinguish them from regular functions.

function Person(name, age) {
  this.name = name;
  this.age = age;
}

To create a new instance of an object using the constructor function, you use the new keyword before the function call.

const person1 = new Person('Alice', 30);
const person2 = new Person('Bob', 25);

Constructor functions, which create new object instances, must only be called with new. Non-constructor functions must not. Mixing these two usages could lead to unexpected results at runtime.

function getNum() {
  return 5;
}

function Num(numeric, alphabetic) {
  this.numeric = numeric;
  this.alphabetic = alphabetic;
}

const num1 = getNum();
const num2 = new getNum(); // Noncompliant: An empty object is returned, not 5

const obj1 = new Num();
const obj2 = Num(); // Noncompliant: undefined is returned, not an object

The rule checks that the new operator is consistently used with each function’s invocations, meaning for all invocations or none.

Resources

Documentation





© 2015 - 2025 Weber Informatics LLC | Privacy Policy