Skip to content

Commit b8c847d

Browse files
authored
Added reasoning for String() and Number()
1 parent 4f44115 commit b8c847d

File tree

1 file changed

+7
-3
lines changed

1 file changed

+7
-3
lines changed

README.md

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3556,7 +3556,9 @@
35563556
- [22.1](#coercion--explicit) Perform type coercion at the beginning of the statement.
35573557

35583558
<a name="coercion--strings"></a><a name="22.2"></a>
3559-
- [22.2](#coercion--strings) Strings: eslint: [`no-new-wrappers`](https://eslint.org/docs/rules/no-new-wrappers)
3559+
- [22.2](#coercion--strings) Strings: Prefer [`String()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) over [`.toString()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString) eslint: [`no-new-wrappers`](https://eslint.org/docs/rules/no-new-wrappers)
3560+
3561+
> Why? `.toString()` is a prototype of `Number`. `String()` on the other hand, is globally available and thus allows casting of any type. Also, `.toString()` can be overridden as seen in [section 9.4](#constructors--tostring)
35603562

35613563
```javascript
35623564
// => this.reviewScore = 9;
@@ -3575,7 +3577,9 @@
35753577
```
35763578

35773579
<a name="coercion--numbers"></a><a name="22.3"></a>
3578-
- [22.3](#coercion--numbers) Numbers: Use `Number` for type casting and `parseInt` always with a radix for parsing strings. eslint: [`radix`](https://eslint.org/docs/rules/radix) [`no-new-wrappers`](https://eslint.org/docs/rules/no-new-wrappers)
3580+
- [22.3](#coercion--numbers) Numbers: Use [`Number()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number) for type casting and [`parseInt()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt) only with a radix for parsing strings. Do prefer `Number()` over `parseInt()` though. eslint: [`radix`](https://eslint.org/docs/rules/radix) [`no-new-wrappers`](https://eslint.org/docs/rules/no-new-wrappers)
3581+
3582+
> Why? Mostly because of the same reasons listed in [the section above](#coercion--strings). Also, since `parseInt()` always expects a string, it does show odd behaviour when parsing very small numbers ([source](https://dmitripavlutin.com/parseint-mystery-javascript/))
35793583

35803584
```javascript
35813585
const inputValue = "4";
@@ -3592,7 +3596,7 @@
35923596
// bad
35933597
const val = parseInt(inputValue);
35943598
3595-
// good
3599+
// best
35963600
const val = Number(inputValue);
35973601
35983602
// good

0 commit comments

Comments
 (0)