From 0daced5fd585ccaed53bb9e14e643be8c78c6608 Mon Sep 17 00:00:00 2001 From: Marcin Kopa Date: Fri, 15 Mar 2019 10:45:05 +0100 Subject: [PATCH 1/2] Fix isNumber snippet and add test for NaN value --- snippets/isNumber.md | 7 ++++--- test/isNumber.test.js | 3 +++ 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/snippets/isNumber.md b/snippets/isNumber.md index 8e02406af..a692c8f9a 100644 --- a/snippets/isNumber.md +++ b/snippets/isNumber.md @@ -2,13 +2,14 @@ Checks if the given argument is a number. -Use `typeof` to check if a value is classified as a number primitive. +Use `typeof` to check if a value is classified as a number primitive. Because `typeof NaN` is equal to `number`, the `val === val` is for protection. NaN compares unequal (via ==, !=, ===, and !==) to any other value, including to another NaN value. ```js -const isNumber = val => typeof val === 'number'; +const isNumber = val => typeof val === 'number' && val === val; ``` ```js -isNumber('1'); // false isNumber(1); // true +isNumber('1'); // false +isNumber(NaN); // false ``` diff --git a/test/isNumber.test.js b/test/isNumber.test.js index 4f27fe9ca..90ca4ec6c 100644 --- a/test/isNumber.test.js +++ b/test/isNumber.test.js @@ -10,3 +10,6 @@ test('passed argument is a number', () => { test('passed argument is not a number', () => { expect(isNumber('1')).toBeFalsy(); }); +test('passed argument is not a number', () => { + expect(isNumber(NaN)).toBeFalsy(); +}); From a5b0abeb360acd4eb0111ba496fa3271b5b95701 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Tue, 19 Mar 2019 09:41:49 +0200 Subject: [PATCH 2/2] Update isNumber.md --- snippets/isNumber.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/snippets/isNumber.md b/snippets/isNumber.md index a692c8f9a..ff0bfe9b9 100644 --- a/snippets/isNumber.md +++ b/snippets/isNumber.md @@ -2,7 +2,8 @@ Checks if the given argument is a number. -Use `typeof` to check if a value is classified as a number primitive. Because `typeof NaN` is equal to `number`, the `val === val` is for protection. NaN compares unequal (via ==, !=, ===, and !==) to any other value, including to another NaN value. +Use `typeof` to check if a value is classified as a number primitive. +To safeguard against `NaN`, check if `val === val` (as `NaN` has a `typeof` equal to `number` and is the only value not equal to itself). ```js const isNumber = val => typeof val === 'number' && val === val;