Skip to content

Latest commit

 

History

History
133 lines (94 loc) · 5.23 KB

prefer-number-properties.md

File metadata and controls

133 lines (94 loc) · 5.23 KB

prefer-number-properties

📝 Prefer Number static methods over global functions and optionally static properties over global constants.

💼 This rule is enabled in the following configs: ✅ recommended, ☑️ unopinionated.

🔧💡 This rule is automatically fixable by the --fix CLI option and manually fixable by editor suggestions.

ECMAScript 2015 moved global number functions onto the Number constructor for consistency and to slightly improve them. This rule enforces their usage to limit the usage of globals:

Use prefer-global-number-constants if you want to enforce the shorter global forms for NaN, Infinity, and -Infinity.

Examples

// ❌
const foo = parseInt('10', 2);

// ✅
const foo = Number.parseInt('10', 2);
// ❌
const foo = parseFloat('10.5');

// ✅
const foo = Number.parseFloat('10.5');
// ❌
const foo = isNaN(10);

// ✅
const foo = Number.isNaN(10);
// ❌
const foo = isFinite(10);

// ✅
const foo = Number.isFinite(10);
// ✅
const foo = Number.parseInt('10', 2);
// ✅
const foo = parseInt('10', 10);

Base-10 parseInt() calls are handled by prefer-number-coercion, which also suggests Number() for parseFloat() (with slightly different semantics).

// ✅
const {parseInt} = Number;
const foo = parseInt('10', 2);
// ✅
const isPositiveZero = value => value === 0 && 1 / value === Infinity;
// ✅
const isNegativeZero = value => value === 0 && 1 / value === -Infinity;

Options

Type: object

Caution

checkNaN and checkInfinity enforce the opposite of prefer-global-number-constants, which is enabled in the recommended and unopinionated configs. If you prefer the Number.* constant forms, disable prefer-global-number-constants to avoid conflicting reports.

checkInfinity

Type: boolean
Default: false

Pass checkInfinity: true to enable check on Infinity.

/* eslint unicorn/prefer-number-properties: ["error", {"checkInfinity": true}] */

// ❌
const foo = Infinity;

// ✅
const foo = Number.POSITIVE_INFINITY;
// ❌
const foo = -Infinity;

// ✅
const foo = Number.NEGATIVE_INFINITY;

checkNaN

Type: boolean
Default: false

Pass checkNaN: true to enable check on NaN.

/* eslint unicorn/prefer-number-properties: ["error", {"checkNaN": true}] */

// ❌
const foo = NaN;

// ✅
const foo = Number.NaN;