]> git.proxmox.com Git - pve-eslint.git/blame - eslint/docs/src/rules/prefer-numeric-literals.md
import 8.41.0 source
[pve-eslint.git] / eslint / docs / src / rules / prefer-numeric-literals.md
CommitLineData
8f9d1d4d
DC
1---
2title: prefer-numeric-literals
8f9d1d4d
DC
3rule_type: suggestion
4---
5
6
eb39fafa
DC
7
8The `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
110b111110111 === 503;
120o767 === 503;
13```
14
15## Rule Details
16
17This 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
19Examples of **incorrect** code for this rule:
20
8f9d1d4d
DC
21::: incorrect
22
eb39fafa
DC
23```js
24/*eslint prefer-numeric-literals: "error"*/
25
26parseInt("111110111", 2) === 503;
27parseInt(`111110111`, 2) === 503;
28parseInt("767", 8) === 503;
29parseInt("1F7", 16) === 503;
30Number.parseInt("111110111", 2) === 503;
31Number.parseInt("767", 8) === 503;
32Number.parseInt("1F7", 16) === 503;
33```
34
8f9d1d4d
DC
35:::
36
eb39fafa
DC
37Examples of **correct** code for this rule:
38
8f9d1d4d
DC
39::: correct
40
eb39fafa
DC
41```js
42/*eslint prefer-numeric-literals: "error"*/
43/*eslint-env es6*/
44
45parseInt(1);
46parseInt(1, 3);
47Number.parseInt(1);
48Number.parseInt(1, 3);
49
500b111110111 === 503;
510o767 === 503;
520x1F7 === 503;
53
54a[parseInt](1,2);
55
56parseInt(foo);
57parseInt(foo, 2);
58Number.parseInt(foo);
59Number.parseInt(foo, 2);
60```
61
8f9d1d4d
DC
62:::
63
eb39fafa
DC
64## When Not To Use It
65
66If 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)