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!
Possibly Related posts:
- Useful trim prototype (function) in core javascript
Below is the most commonly used trim prototype/function in javascript. Posting for reference. String.prototype.trim = function() { return this.replace(/(^\s*)|(\s*$)/g,"") } You can place the above... - Validating php multiple-value checkbox form element with javascript
In php a multiple-value form element such as checkbox is named suffixed with a set of square brackets. For example, My commonly used colors are:... - Browser detect script in javascript
I found this useful and up-to-date article to detect browser in JavaScript. Please refer to the author’s site page for detailed explanation. The site (http://www.quirksmode.org/)... - Getting next day date in javascript
Here is an useful function to get next day’s date string in javascript. I am going to explain each line of code for those who...
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.





