Prefer Number Static Methods
ID |
javascript.prefer_number_static_methods |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Best Practice |
Language |
JavaScript |
Tags |
best-practice, numeric, simplification |
Description
Reports a call to one of the four numeric globals that Number also carries: parseInt, parseFloat, isNaN and isFinite.
const n = parseInt(input, 10); // FLAW
if (isNaN(value)) { } // FLAW
Only a bare call is reported. A call through a receiver — Number.parseInt(…), window.parseInt(…) — is already namespaced, and a call that resolves to a function declared in the file is a local of the same name rather than the global.
Rationale
The two pairs earn the report for different reasons.
-
Number.parseIntandNumber.parseFloatare specified to be the same function objects as the globals. The change is about saying where the operation comes from: a bareparseIntin a module reads like an import someone forgot to add. -
isNaNandisFiniteare the ones that matter. The globals coerce their argument to a number first, soisNaN("hello")istrueandisFinite("42")istrue— they answer a question about the coercion, not about the value.Number.isNaNandNumber.isFinitedo not coerce; they answerfalsefor anything that is not already a number, which is what the call site nearly always meant.