Javascript common mistake of comparing with NaN and not with isNaN

Recently, i fell into the trap of NaN and isNaN and it turned me pulling my hair for quite a few good minutes. Thats why i decided to make a note of it here for a recitation and as a note of reference for myself for future.

Here’s how it comes. Suppose you are doing some string manipulation and it resulted into NaN (Not-a-Number type). For example, parsing a “string” as an integer using javascript’s parseInt function would result into a NaN.

var x = parseInt("Hello"); //this would label your variable x as NaN.

Now suppose you wanted to check whether x is NaN or not. Having not looked at the isNaN and/or NaN earlier carefully (like me) you may simply fell into this trap and may try to compare x with NaN like this:

if(x==NaN) - incorrect
if(x=="NaN") - incorrect

Solution

Always use isNaN to compare NaN value.

if(isNaN(x)) - correct, works!
Share

Possibly Related posts:

Tags : , , ,

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Leave Comment

Freelance Jobs