Add Number.isNaN and Number.isFinite

This commit is contained in:
Alexey Chilipenko 2022-08-01 17:12:02 +03:00 committed by GitHub
parent 7000ede297
commit abaaae5f28
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -334,6 +334,35 @@ alert( isFinite(num) );
Please note that an empty or a space-only string is treated as `0` in all numeric functions including `isFinite`. Please note that an empty or a space-only string is treated as `0` in all numeric functions including `isFinite`.
````smart header="`Number.isNaN` and `Number.isFinite`"
[Number.isNaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN) and [Number.isFinite](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite) methods are the more "strict" versions of `isNaN` and `isFinite` functions. They do not autoconvert their argument into a number, but check if it belongs to the `number` type instead.
- `Number.isNaN(value)` returns `true` if the argument belongs to the `number` type and it is `NaN`. In any other case it returns `false`.
```js run
alert( Number.isNaN(NaN) ); // true
alert( Number.isNaN("str" / 2) ); // true
// Note the difference:
alert( Number.isNaN("str") ); // false, because "str" belongs to the string type, not the number type
alert( isNaN("str") ); // true, because isNaN converts string "str" into a number and gets NaN as a result of this conversion
```
- `Number.isFinite(value)` returns `true` if the argument belongs to the `number` type and it is not `NaN/Infinity/-Infinity`. In any other case it returns `false`.
```js run
alert( Number.isFinite(123) ); // true
alert( Number.isFinite(Infinity) ); //false
alert( Number.isFinite(2 / 0) ); // false
// Note the difference:
alert( Number.isFinite("123") ); // false, because "123" belongs to the string type, not the number type
alert( isFinite("123") ); // true, because isFinite converts string "123" into a number 123
```
Do not consider `Number.isNaN` and `Number.isFinite` methods as the more "correct" versions of `isNaN` and `isFinite` functions. They complement each other and are equally essential for different tasks.
````
```smart header="Compare with `Object.is`" ```smart header="Compare with `Object.is`"
There is a special built-in method `Object.is` that compares values like `===`, but is more reliable for two edge cases: There is a special built-in method `Object.is` that compares values like `===`, but is more reliable for two edge cases: