]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/src/rules/prefer-numeric-literals.md
33109f50ae8c59e19e112dd521e34acbb904c8d2
[pve-eslint.git] / eslint / docs / src / rules / prefer-numeric-literals.md
1 ---
2 title: prefer-numeric-literals
3 layout: doc
4 rule_type: suggestion
5 ---
6
7
8
9 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()`.
10
11 ```js
12 0b111110111 === 503;
13 0o767 === 503;
14 ```
15
16 ## Rule Details
17
18 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).
19
20 Examples of **incorrect** code for this rule:
21
22 ::: incorrect
23
24 ```js
25 /*eslint prefer-numeric-literals: "error"*/
26
27 parseInt("111110111", 2) === 503;
28 parseInt(`111110111`, 2) === 503;
29 parseInt("767", 8) === 503;
30 parseInt("1F7", 16) === 503;
31 Number.parseInt("111110111", 2) === 503;
32 Number.parseInt("767", 8) === 503;
33 Number.parseInt("1F7", 16) === 503;
34 ```
35
36 :::
37
38 Examples of **correct** code for this rule:
39
40 ::: correct
41
42 ```js
43 /*eslint prefer-numeric-literals: "error"*/
44 /*eslint-env es6*/
45
46 parseInt(1);
47 parseInt(1, 3);
48 Number.parseInt(1);
49 Number.parseInt(1, 3);
50
51 0b111110111 === 503;
52 0o767 === 503;
53 0x1F7 === 503;
54
55 a[parseInt](1,2);
56
57 parseInt(foo);
58 parseInt(foo, 2);
59 Number.parseInt(foo);
60 Number.parseInt(foo, 2);
61 ```
62
63 :::
64
65 ## When Not To Use It
66
67 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.
68
69 ## Compatibility
70
71 * **JSCS**: [requireNumericLiterals](https://jscs-dev.github.io/rule/requireNumericLiterals)