noConstructorReturn
Summary
Section titled “Summary”- Rule available since:
v1.0.0
- Diagnostic Category:
lint/correctness/noConstructorReturn
- This rule is recommended, which means is enabled by default.
- This rule doesn’t have a fix.
- The default severity of this rule is error.
- Sources:
- Same as
no-constructor-return
- Same as
Description
Section titled “Description”Disallow returning a value from a constructor
.
Returning a value from a constructor
of a class is a possible error.
Forbidding this pattern prevents errors resulting from unfamiliarity with JavaScript or a copy-paste error.
Only returning without a value is allowed, as it’s a control flow statement.
Examples
Section titled “Examples”Invalid
Section titled “Invalid”class A { constructor() { return 0; }}
code-block.js:3:9 lint/correctness/noConstructorReturn ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ The constructor should not return a value.
1 │ class A {
2 │ constructor() {
> 3 │ return 0;
│ ^^^^^^^^^
4 │ }
5 │ }
ℹ The constructor is here:
1 │ class A {
> 2 │ constructor() {
│ ^^^^^^^^^^^^^^^
> 3 │ return 0;
> 4 │ }
│ ^
5 │ }
6 │
ℹ Returning a value from a constructor may confuse users of the class.
class A { constructor() {}}
class B { constructor(x) { return; }}
Using this rule in combination with the singleton pattern
Section titled “Using this rule in combination with the singleton pattern”Some people implement the singleton pattern in JavaScript by returning an existing instance from the constructor, which would conflict with this rule.
Instead, we advise to follow one of the suggestions described in this blog post: https://arendjr.nl/blog/2024/11/singletons-in-javascript/
How to configure
Section titled “How to configure”{ "linter": { "rules": { "correctness": { "noConstructorReturn": "error" } } }}