Maintaining Code Quality with ESLint: Understanding the no-new Rule
- Avoiding Unnecessary Code
When you usenew
and discard the object, it can potentially be a sign that the code could be simplified by using a function that doesn't requirenew
. - Maintaining Consistency
By enforcing proper usage ofnew
, ESLint helps keep your code consistent and easier to understand.
function someFunction() {
new String("hello"); // This would trigger the no-new rule
}
In this case, creating a new String object with new
and then not storing it is pointless. You could simply write "hello"
directly.
However, there are situations where no-new
might not be ideal:
- Custom Implementations
If you have a custom implementation of a constructor that requiresnew
, you might need to disableno-new
for specific parts of your code.
ESLint offers other related rules that focus on specific uses of new
:
no-new-wrappers
: Focuses on avoiding primitive wrapper objects likenew String()
,new Number()
, andnew Boolean()
where unnecessary.no-new-require
(from theeslint-plugin-n
plugin): Discourages usingnew require
in Node.js environments.no-new-symbol
: Prevents accidental creation of symbols withnew Symbol()
.
Incorrect Code (throws away the object)
// Using new without storing the result (triggers no-new)
new String("hello");
new Number(42);
new Boolean(true); // Can be written as just `true`
// Side effect, not storing the object (might trigger no-new depending on configuration)
Math.random(); // Math.random() has side effects, may or may not be flagged
// Deprecated usage (not recommended, might trigger no-new)
new Function("a", "b", "return a + b"); // Use arrow functions instead
// Storing the created object
const myString = new String("hello");
const age = new Number(42);
const isTrue = new Boolean(true); // Still discouraged, use `true` directly
// No need for new with Math functions
const randomNumber = Math.random();
// Modern function definition (avoids no-new)
const add = (a, b) => a + b;
- Configure no-new Severity
- You can adjust the severity of the
no-new
rule in your ESLint configuration. Instead of an error (which halts linting), you could set it to a warning that flags potential issues but allows the code to lint successfully.
- Disable no-new for Specific Code
- If you have a specific code section requiring
new
for valid reasons (like custom constructors), you can use ESLint comments to disableno-new
locally for those parts.
- Use Related Rules
- Consider using more specific ESLint rules that target similar scenarios:
no-new-symbol
: Prevents accidental symbol creation withnew Symbol()
.no-new-require
(fromeslint-plugin-n
): Discouragesnew require
in Node.js.no-new-wrappers
: Targets avoiding unnecessary primitive wrappers likenew String()
.
- Custom ESLint Rule (Advanced)
- For very specific needs, you can create a custom ESLint rule that defines your own criteria for when
new
is acceptable. This requires advanced knowledge of ESLint rule development.