noMagicNumbers
Esta página aún no está disponible en tu idioma.
Summary
Section titled “Summary”- Rule available since:
v2.1.0
- Diagnostic Category:
lint/nursery/noMagicNumbers
- This rule doesn’t have a fix.
- The default severity of this rule is information.
- Sources:
Description
Section titled “Description”Reports usage of “magic numbers” — numbers used directly instead of being assigned to named constants.
Its goal is to improve code maintainability and readability by encouraging developers to extract such numbers into named constants, making their purpose explicit.
It ignores:
- non-magic values (like 0, 1, 2, 10, 24, 60, and their negative or bigint forms) found anywhere, including arithmetic expressions, fn calls etc.
- Array indices
- Enum values
- Initial values in variable or class property declarations
- Default values in function parameters or destructuring patterns
- Arguments to JSON.stringify and parseInt (e.g.,
JSON.stringify(22)
,parseInt("123", 8)
) - Operands in bitwise operations (e.g.,
a & 7
,a | 7
) - Values in JSX expressions (e.g.,
<div>{1}</div>
) - Object property values (e.g.,
{ tax: 0.25 }
)
Examples
Section titled “Examples”Invalid
Section titled “Invalid”let total = price * 1.23; // Magic number for tax rate
code-block.js:1:21 lint/nursery/noMagicNumbers ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
ℹ Magic number detected. Extract it to a constant with a meaningful name.
> 1 │ let total = price * 1.23; // Magic number for tax rate
│ ^^^^
2 │
ℹ Code is more readable and refactoring easier when special numbers are declared as constants as it makes their meaning explicit.
const TAX_RATE = 1.23;let total = price * TAX_RATE;
How to configure
Section titled “How to configure”{ "linter": { "rules": { "nursery": { "noMagicNumbers": "error" } } }}