From abaaae5f28bfed3b654ec10c13b45e218bbe5296 Mon Sep 17 00:00:00 2001 From: Alexey Chilipenko <5251053+chilipenko@users.noreply.github.com> Date: Mon, 1 Aug 2022 17:12:02 +0300 Subject: [PATCH] Add Number.isNaN and Number.isFinite --- 1-js/05-data-types/02-number/article.md | 29 +++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/1-js/05-data-types/02-number/article.md b/1-js/05-data-types/02-number/article.md index 3fec8848..37980e41 100644 --- a/1-js/05-data-types/02-number/article.md +++ b/1-js/05-data-types/02-number/article.md @@ -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`. +````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`" There is a special built-in method `Object.is` that compares values like `===`, but is more reliable for two edge cases: