]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/src/rules/prefer-numeric-literals.md
import 8.41.0 source
[pve-eslint.git] / eslint / docs / src / rules / prefer-numeric-literals.md
1 ---
2 title: prefer-numeric-literals
3 rule_type: suggestion
4 ---
5
6
7
8 The `parseInt()` and `Number.parseInt()` functions can be used to turn binary, octal, and hexadecimal strings into integers. As binary, octal, and hexadecimal literals are supported in ES6, this rule encourages use of those numeric literals instead of `parseInt()` or `Number.parseInt()`.
9
10 ```js
11 0b111110111 === 503;
12 0o767 === 503;
13 ```
14
15 ## Rule Details
16
17 This rule disallows calls to `parseInt()` or `Number.parseInt()` if called with two arguments: a string; and a radix option of 2 (binary), 8 (octal), or 16 (hexadecimal).
18
19 Examples of **incorrect** code for this rule:
20
21 ::: incorrect
22
23 ```js
24 /*eslint prefer-numeric-literals: "error"*/
25
26 parseInt("111110111", 2) === 503;
27 parseInt(`111110111`, 2) === 503;
28 parseInt("767", 8) === 503;
29 parseInt("1F7", 16) === 503;
30 Number.parseInt("111110111", 2) === 503;
31 Number.parseInt("767", 8) === 503;
32 Number.parseInt("1F7", 16) === 503;
33 ```
34
35 :::
36
37 Examples of **correct** code for this rule:
38
39 ::: correct
40
41 ```js
42 /*eslint prefer-numeric-literals: "error"*/
43 /*eslint-env es6*/
44
45 parseInt(1);
46 parseInt(1, 3);
47 Number.parseInt(1);
48 Number.parseInt(1, 3);
49
50 0b111110111 === 503;
51 0o767 === 503;
52 0x1F7 === 503;
53
54 a[parseInt](1,2);
55
56 parseInt(foo);
57 parseInt(foo, 2);
58 Number.parseInt(foo);
59 Number.parseInt(foo, 2);
60 ```
61
62 :::
63
64 ## When Not To Use It
65
66 If you want to allow use of `parseInt()` or `Number.parseInt()` for binary, octal, or hexadecimal integers, or if you are not using ES6 (because binary and octal literals are not supported in ES5 and below), you may wish to disable this rule.
67
68 ## Compatibility
69
70 * **JSCS**: [requireNumericLiterals](https://jscs-dev.github.io/rule/requireNumericLiterals)