Weird Behavior of isNaN() in JavaScript.

Outputs of isNaN() that may surprising you !

·

2 min read

Weird Behavior of isNaN() in JavaScript.

In this article, I have covered** 9 scenarios to check how isNaN() is behave with different inputs**.

Let's see it one by one :

I have divided this article into 2 parts

A) isNaN() working as per our expectation.

B) Weird behavior of isNaN().


A) isNaN() working as per our expectation.

  1. isNaN() function without any argument.
isNaN();

It's obvious, an undefined value will be passed as an argument so the output will be true and its.

  1. isNaN() function with an Integer value.
isNaN(1);

yes, its also crystal clear, the function will give output as false.

  1. isNaN() function with empty object ({}).
isNaN({});

JavaScript object is also not a number so it'll give you true value.


B) Weird behavior of isNaN() starts here...

  1. isNaN() function with empty array ([]).
isNaN([]);

It gives **false ** as output.

  1. isNaN() function with a null keyword.
isNaN(null);

It'll give false.

  1. What do you think about Boolean keywords(true and false)
isNaN(true);
isNaN(false);

It generates a false value.

  1. isNaN() with date isNaN(new Date()) This will generate true, according to the Mozilla developer guide date can be converted to a number, so that's why it gave false.

  2. isNaN() with Empty string.

isNaN("");

//false: the empty string is converted to 0 which is not NaN

What was my motivation to write this article?

I was doing some experiments on lodash repository function ( Lodash is a popular javascript-based library that provides 200+ functions to facilitate web development. )

Look at below code snippet - ``` function compact1(array) { if(isNaN(array)){ let resIndex = 0 const result = []

if (array == null) { console.log("here =" ,array); return result }

for (const value of array) { if (value) { result[resIndex++] = value } } return result } return "Please pass an array as an argument"; } //Note: I have modified this code for doing some experiments. ```

The above function will return only the truthy value from the array.

like

compact([0, 1, false, 2, '', 3])

// output=> [1, 2, 3]

  • But then I thought let's just pass an integer number and empty array to the above function,

like,

compact([])
 *// output=> ="Please pass array as an argument"

But surprisingly, internally somehow it was considered as numbered.

If you know why JS behaves weirdly in some cases please write in the comments.

Thank you.