Code of the Day: Javascript, Fix for isNaN


Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: Undefined array key "layout" in /home/bateeqjg/public_html/news/wp-content/plugins/wp-about-author/wp-about-author.php on line 94

Javascript is a dynamically typed langauges. This feature causes for Arrays, Booleans, and other types to be converted to a numeric values depending on usage.
However this feature can cause headarches when trying to detect numbers.

For example, isNaN() detects if a value is a non-number. That’s what NaN stands for, “Not a number”.
So you might think that the opposite result from isNaN() would indicate if a value is a number.

// Works for most cases but not for strict comparisons.
var isNumber = function(val){
	return !isNaN( val );
};

Example:
Note: Click the “result” tab to run the test cases in jsfiddle.net.

Solution:
So here’s a simple fix for isNaN and isNumber.

// isNaN2 returns a boolean for if a value is not a number or +-Infinity
var isNaN2 = (function (global) {
    var _isNaN = global.isNaN;
    return function (val) {
        return _isNaN("" + val) || (typeof val === "object" && !(val || "").hasOwnProperty('push'));
    };
}(this));
// isNumeric returns a boolean for if a value is a number or +-Infinity
var isNumeric = (function (global) {
    var _isNaN = global.isNaN;
    return function (val) {
        return !_isNaN("" + val)&&(typeof val !== "object" || (val || "").hasOwnProperty('push'));
    };
}(this));


isNaN vs isNaN2

Testcases for isNaN2 and isNumeric

*Update*
Well it turns out that jQuery has a better implementation. The only difference is that infinity is not a number, which is correct.

$.isNumeric = function( obj ){
    return !isNaN( parseFloat( obj ) ) && isFinite( obj );
};


api.jquery.com/jQuery.isNumeric

Larry Battle

Larry Battle

I love to program, and discover new tech. Check out my <a href="http://stackoverflow.com/users/527776/larry-battle">stackoverflow</a> and <a href="https://github.com/LarryBattle">github</a> accounts.

More Posts - Website

Follow Me:Add me on XAdd me on LinkedInAdd me on YouTube