Can I convert a string representing a boolean value (e.g., 'true', 'false') into a intrinsic type in JavaScript?
I have a hidden form in HTML that is updated based upon a user's selection within a list. This form contains some fields which represent boolean values and are dynamically populated with an intrinsic boolean value. However, once this value is placed into the hidden input field it becomes a string.
The only way I could find to determine the field's boolean value, once it was converted into a string, was to depend upon the literal value of its string representation.
var myValue = document.myForm.IS_TRUE.value;
var isTrueSet = myValue == 'true';
Is there a better way to accomplish this?
Do:
var isTrueSet = (myValue === 'true');
using the identity operator (===), which doesn't make any implicit type conversions when the compared variables have different types.
This will set isTrueSet to a boolean true if the string is "true" and boolean false if it is string "false" or not set at all.
For making it case-insensitive, try:
var isTrueSet = /^true$/i.test(myValue);
// or
var isTrueSet = (myValue?.toLowerCase?.() === 'true');
// or
var isTrueSet = (String(myValue).toLowerCase() === 'true');
Don't:
You should probably be cautious about using these two methods for your specific needs:
var myBool = Boolean("false"); // == true
var myBool = !!"false"; // == true
Any string which isn't the empty string will evaluate to true by using them. Although they're the cleanest methods I can think of concerning to boolean conversion, I think they're not what you're looking for.
Warning
This highly upvoted legacy answer is technically correct but only covers a very specific scenario, when your string value is EXACTLY "true" or "false".
An invalid json string passed into these functions below WILL throw an exception.
Original answer:
How about?
JSON.parse("True".toLowerCase());
or with jQuery
$.parseJSON("TRUE".toLowerCase());
const stringToBoolean = (stringValue) => {
switch(stringValue?.toLowerCase()?.trim()){
case "true":
case "yes":
case "1":
return true;
case "false":
case "no":
case "0":
case null:
case undefined:
return false;
default:
return JSON.parse(stringValue);
}
}
I think this is much universal:
if (String(a).toLowerCase() == "true") ...
It goes:
String(true) == "true" //returns true
String(false) == "true" //returns false
String("true") == "true" //returns true
String("false") == "true" //returns false
Remember to match case:
var isTrueSet = (myValue.toLowerCase() === 'true');
Also, if it's a form element checkbox, you can also detect if the checkbox is checked:
var isTrueSet = document.myForm.IS_TRUE.checked;
Assuming that if it is checked, it is "set" equal to true. This evaluates as true/false.
This is the easiest way to do boolean conversion I came across recently. Thought of adding it.
JSON.parse('true');
let trueResponse = JSON.parse('true');
let falseResponse = JSON.parse('false');
console.log(trueResponse);
console.log(falseResponse);
You can use regular expressions:
/*
* Converts a string to a bool.
*
* This conversion will:
*
* - match 'true', 'on', or '1' as true.
* - ignore all white-space padding
* - ignore capitalization (case).
*
* ' tRue ','ON', and '1 ' will all evaluate as true.
*
*/
function strToBool(s)
{
// will match one and only one of the string 'true','1', or 'on' rerardless
// of capitalization and regardless off surrounding white-space.
//
regex=/^\s*(true|1|on)\s*$/i
return regex.test(s);
}
If you like extending the String class you can do:
String.prototype.bool = function() {
return strToBool(this);
};
alert("true".bool());
For those (see the comments) that would like to extend the String object to get this but are worried about enumerability and are worried about clashing with other code that extends the String object:
Object.defineProperty(String.prototype, "com_example_bool", {
get : function() {
return (/^(true|1)$/i).test(this);
}
});
alert("true".com_example_bool);
(Won't work in older browsers of course and Firefox shows false while Opera, Chrome, Safari and IE show true. Bug 720760)
Wood-eye be careful.
After seeing the consequences after applying the top answer with 500+ upvotes, I feel obligated to post something that is actually useful:
Let's start with the shortest, but very strict way:
var str = "true";
var mybool = JSON.parse(str);
And end with a proper, more tolerant way:
var parseBool = function(str, strict)
{
// console.log(typeof str);
// strict: JSON.parse(str)
if (str == null)
{
if (strict)
throw new Error("Parameter 'str' is null or undefined.");
return false;
}
if (typeof str === 'boolean')
{
return (str === true);
}
if(typeof str === 'string')
{
if(str == "")
return false;
str = str.replace(/^\s+|\s+$/g, '');
if(str.toLowerCase() == 'true' || str.toLowerCase() == 'yes')
return true;
str = str.replace(/,/g, '.');
str = str.replace(/^\s*\-\s*/g, '-');
}
// var isNum = string.match(/^[0-9]+$/) != null;
// var isNum = /^\d+$/.test(str);
if(!isNaN(str))
return (parseFloat(str) != 0);
return false;
}
Testing:
var array_1 = new Array(true, 1, "1",-1, "-1", " - 1", "true", "TrUe", " true ", " TrUe", 1/0, "1.5", "1,5", 1.5, 5, -3, -0.1, 0.1, " - 0.1", Infinity, "Infinity", -Infinity, "-Infinity"," - Infinity", " yEs");
var array_2 = new Array(null, "", false, "false", " false ", " f alse", "FaLsE", 0, "00", "1/0", 0.0, "0.0", "0,0", "100a", "1 00", " 0 ", 0.0, "0.0", -0.0, "-0.0", " -1a ", "abc");
for(var i =0; i < array_1.length;++i){ console.log("array_1["+i+"] ("+array_1[i]+"): " + parseBool(array_1[i]));}
for(var i =0; i < array_2.length;++i){ console.log("array_2["+i+"] ("+array_2[i]+"): " + parseBool(array_2[i]));}
for(var i =0; i < array_1.length;++i){ console.log(parseBool(array_1[i]));}
for(var i =0; i < array_2.length;++i){ console.log(parseBool(array_2[i]));}
I thought that #Steven 's answer was the best one, and took care of a lot more cases than if the incoming value was just a string. I wanted to extend it a bit and offer the following:
function isTrue(value){
if (typeof(value) === 'string'){
value = value.trim().toLowerCase();
}
switch(value){
case true:
case "true":
case 1:
case "1":
case "on":
case "yes":
return true;
default:
return false;
}
}
It's not necessary to cover all the false cases if you already know all of the true cases you'd have to account for. You can pass anything into this method that could pass for a true value (or add others, it's pretty straightforward), and everything else would be considered false
Universal solution with JSON parse:
function getBool(val) {
return !!JSON.parse(String(val).toLowerCase());
}
getBool("1"); //true
getBool("0"); //false
getBool("true"); //true
getBool("false"); //false
getBool("TRUE"); //true
getBool("FALSE"); //false
UPDATE (without JSON):
function getBool(val){
var num = +val;
return !isNaN(num) ? !!num : !!String(val).toLowerCase().replace(!!0,'');
}
I also created fiddle to test it http://jsfiddle.net/remunda/2GRhG/
Your solution is fine.
Using === would just be silly in this case, as the field's value will always be a String.
The Boolean object doesn't have a 'parse' method. Boolean('false') returns true, so that won't work. !!'false' also returns true, so that won't work also.
If you want string 'true' to return boolean true and string 'false' to return boolean false, then the simplest solution is to use eval(). eval('true') returns true and eval('false') returns false.
Keep in mind the performance and security implications when using eval() though.
var falsy = /^(?:f(?:alse)?|no?|0+)$/i;
Boolean.parse = function(val) {
return !falsy.test(val) && !!val;
};
This returns false for every falsy value and true for every truthy value except for 'false', 'f', 'no', 'n', and '0' (case-insensitive).
// False
Boolean.parse(false);
Boolean.parse('false');
Boolean.parse('False');
Boolean.parse('FALSE');
Boolean.parse('f');
Boolean.parse('F');
Boolean.parse('no');
Boolean.parse('No');
Boolean.parse('NO');
Boolean.parse('n');
Boolean.parse('N');
Boolean.parse('0');
Boolean.parse('');
Boolean.parse(0);
Boolean.parse(null);
Boolean.parse(undefined);
Boolean.parse(NaN);
Boolean.parse();
//True
Boolean.parse(true);
Boolean.parse('true');
Boolean.parse('True');
Boolean.parse('t');
Boolean.parse('yes');
Boolean.parse('YES');
Boolean.parse('y');
Boolean.parse('1');
Boolean.parse('foo');
Boolean.parse({});
Boolean.parse(1);
Boolean.parse(-1);
Boolean.parse(new Date());
There are a lot of answers and it's hard to pick one. In my case, I prioritise the performance when choosing, so I create this jsPerf that I hope can throw some light here.
Brief of results (the higher the better):
Conditional statement: 2,826,922
Switch case on Bool object: 2,825,469
Casting to JSON: 1,867,774
!! conversions: 805,322
Prototype of String: 713,637
They are linked to the related answer where you can find more information (pros and cons) about each one; specially in the comments.
This has been taken from the accepted answer, but really it has a very weak point, and I am shocked how it got that count of upvotes, the problem with it that you have to consider the case of the string because this is case sensitive
var isTrueSet = (myValue.toLowerCase() === 'true');
I use the following:
function parseBool(b) {
return !(/^(false|0)$/i).test(b) && !!b;
}
This function performs the usual Boolean coercion with the exception of the strings "false" (case insensitive) and "0".
The expression you're looking for simply is
/^true$/i.test(myValue)
as in
var isTrueSet = /^true$/i.test(myValue);
This tests myValue against a regular expression , case-insensitive, and doesn't modify the prototype.
Examples:
/^true$/i.test("true"); // true
/^true$/i.test("TRUE"); // true
/^true$/i.test("tRuE"); // true
/^true$/i.test(" tRuE"); // false (notice the space at the beginning)
/^true$/i.test("untrue"); // false (some other solutions here will incorrectly return true
/^true$/i.test("false");// returns false
/^true$/i.test("xyz"); // returns false
Simplest solution 🙌🏽
with ES6+
use the logical NOT twice [ !! ] to get the string converted
Just paste this expression...
const stringToBoolean = (string) => string === 'false' ? false : !!string
And pass your string to it!
stringToBoolean('') // false
stringToBoolean('false') // false
stringToBoolean('true') // true
stringToBoolean('hello my friend!') // true
🤙🏽 Bonus! 🤙🏽
const betterStringToBoolean = (string) =>
string === 'false' || string === 'undefined' || string === 'null' || string === '0' ?
false : !!string
You can include other strings at will to easily extend the usage of this expression...:
betterStringToBoolean('undefined') // false
betterStringToBoolean('null') // false
betterStringToBoolean('0') // false
betterStringToBoolean('false') // false
betterStringToBoolean('') // false
betterStringToBoolean('true') // true
betterStringToBoolean('anything else') // true
you can use JSON.parse as follows:
var trueOrFalse='True';
result =JSON.parse(trueOrFalse.toLowerCase());
if(result==true)
alert('this is true');
else
alert('this is false');
in this case .toLowerCase is important
Boolean.parse = function (str) {
switch (str.toLowerCase ()) {
case "true":
return true;
case "false":
return false;
default:
throw new Error ("Boolean.parse: Cannot convert string to boolean.");
}
};
There are already so many answers available. But following can be useful in some scenarios.
// One can specify all values against which you consider truthy
var TRUTHY_VALUES = [true, 'true', 1];
function getBoolean(a) {
return TRUTHY_VALUES.some(function(t) {
return t === a;
});
}
This can be useful where one examples with non-boolean values.
getBoolean('aa'); // false
getBoolean(false); //false
getBoolean('false'); //false
getBoolean('true'); // true
getBoolean(true); // true
getBoolean(1); // true
To convert both string("true", "false") and boolean to boolean
('' + flag) === "true"
Where flag can be
var flag = true
var flag = "true"
var flag = false
var flag = "false"
I'm suprised that includes was not suggested
let bool = "false"
bool = !["false", "0", 0].includes(bool)
You can modify the check for truely or include more conditions (e.g. null, '').
This function can handle string as well as Boolean true/false.
function stringToBoolean(val){
var a = {
'true':true,
'false':false
};
return a[val];
}
Demonstration below:
function stringToBoolean(val) {
var a = {
'true': true,
'false': false
};
return a[val];
}
console.log(stringToBoolean("true"));
console.log(typeof(stringToBoolean("true")));
console.log(stringToBoolean("false"));
console.log(typeof(stringToBoolean("false")));
console.log(stringToBoolean(true));
console.log(typeof(stringToBoolean(true)));
console.log(stringToBoolean(false));
console.log(typeof(stringToBoolean(false)));
console.log("=============================================");
// what if value was undefined?
console.log("undefined result: " + stringToBoolean(undefined));
console.log("type of undefined result: " + typeof(stringToBoolean(undefined)));
console.log("=============================================");
// what if value was an unrelated string?
console.log("unrelated string result: " + stringToBoolean("hello world"));
console.log("type of unrelated string result: " + typeof(stringToBoolean(undefined)));
One Liner
We just need to account for the "false" string since any other string (including "true") is already true.
function b(v){ return v==="false" ? false : !!v; }
Test
b(true) //true
b('true') //true
b(false) //false
b('false') //false
A more exaustive version
function bool(v){ return v==="false" || v==="null" || v==="NaN" || v==="undefined" || v==="0" ? false : !!v; }
Test
bool(true) //true
bool("true") //true
bool(1) //true
bool("1") //true
bool("hello") //true
bool(false) //false
bool("false") //false
bool(0) //false
bool("0") //false
bool(null) //false
bool("null") //false
bool(NaN) //false
bool("NaN") //false
bool(undefined) //false
bool("undefined") //false
bool("") //false
bool([]) //true
bool({}) //true
bool(alert) //true
bool(window) //true
I'm using this one
String.prototype.maybeBool = function(){
if ( ["yes", "true", "1", "on"].indexOf( this.toLowerCase() ) !== -1 ) return true;
if ( ["no", "false", "0", "off"].indexOf( this.toLowerCase() ) !== -1 ) return false;
return this;
}
"on".maybeBool(); //returns true;
"off".maybeBool(); //returns false;
"I like js".maybeBool(); //returns "I like js"
why don't you try something like this
Boolean(JSON.parse((yourString.toString()).toLowerCase()));
It will return an error when some other text is given rather than true or false regardless of the case and it will capture the numbers also as
// 0-> false
// any other number -> true
You need to separate (in your thinking) the value of your selections and the representation of that value.
Pick a point in the JavaScript logic where they need to transition from string sentinels to native type and do a comparison there, preferably where it only gets done once for each value that needs to be converted. Remember to address what needs to happen if the string sentinel is not one the script knows (i.e. do you default to true or to false?)
In other words, yes, you need to depend on the string's value. :-)
Hands down the easiest way (assuming you string will be 'true' or 'false') is:
var z = 'true';
var y = 'false';
var b = (z === 'true'); // will evaluate to true
var c = (y === 'true'); // will evaluate to false
Always use the === operator instead of the == operator for these types of conversions!
Like #Shadow2531 said, you can't just convert it directly. I'd also suggest that you consider string inputs besides "true" and "false" that are 'truthy' and 'falsey' if your code is going to be reused/used by others. This is what I use:
function parseBoolean(string) {
switch (String(string).toLowerCase()) {
case "true":
case "1":
case "yes":
case "y":
return true;
case "false":
case "0":
case "no":
case "n":
return false;
default:
//you could throw an error, but 'undefined' seems a more logical reply
return undefined;
}
}
Related
I’ve only been trying it in Firefox’s JavaScript console, but neither of the following statements return true:
parseFloat('geoff') == NaN;
parseFloat('geoff') == Number.NaN;
Try this code:
isNaN(parseFloat("geoff"))
For checking whether any value is NaN, instead of just numbers, see here: How do you test for NaN in Javascript?
I just came across this technique in the book Effective JavaScript that is pretty simple:
Since NaN is the only JavaScript value that is treated as unequal to itself, you can always test if a value is NaN by checking it for equality to itself:
var a = NaN;
a !== a; // true
var b = "foo";
b !== b; // false
var c = undefined;
c !== c; // false
var d = {};
d !== d; // false
var e = { valueOf: "foo" };
e !== e; // false
Didn't realize this until #allsyed commented, but this is in the ECMA spec: https://tc39.github.io/ecma262/#sec-isnan-number
Use this code:
isNaN('geoff');
See isNaN() docs on MDN.
alert ( isNaN('abcd')); // alerts true
alert ( isNaN('2.0')); // alerts false
alert ( isNaN(2.0)); // alerts false
As far as a value of type Number is to be tested whether it is a NaN or not, the global function isNaN will do the work
isNaN(any-Number);
For a generic approach which works for all the types in JS, we can use any of the following:
For ECMAScript-5 Users:
#1
if(x !== x) {
console.info('x is NaN.');
}
else {
console.info('x is NOT a NaN.');
}
For people using ECMAScript-6:
#2
Number.isNaN(x);
And For consistency purpose across ECMAScript 5 & 6 both, we can also use this polyfill for Number.isNan
#3
//Polyfill from MDN
Number.isNaN = Number.isNaN || function(value) {
return typeof value === "number" && isNaN(value);
}
// Or
Number.isNaN = Number.isNaN || function(value) {
return value !== value;
}
please check This Answer for more details.
You should use the global isNaN(value) function call, because:
It is supported cross-browser
See isNaN for documentation
Examples:
isNaN('geoff'); // true
isNaN('3'); // false
I hope this will help you.
As of ES6, Object.is(..) is a new utility that can be used to test two values for absolute equality:
var a = 3 / 'bar';
Object.is(a, NaN); // true
NaN is a special value that can't be tested like that. An interesting thing I just wanted to share is this
var nanValue = NaN;
if(nanValue !== nanValue) // Returns true!
alert('nanValue is NaN');
This returns true only for NaN values and Is a safe way of testing. Should definitely be wrapped in a function or atleast commented, because It doesnt make much sense obviously to test if the same variable is not equal to each other, hehe.
NaN in JavaScript stands for "Not A Number", although its type is actually number.
typeof(NaN) // "number"
To check if a variable is of value NaN, we cannot simply use function isNaN(), because isNaN() has the following issue, see below:
var myVar = "A";
isNaN(myVar) // true, although "A" is not really of value NaN
What really happens here is that myVar is implicitly coerced to a number:
var myVar = "A";
isNaN(Number(myVar)) // true. Number(myVar) is NaN here in fact
It actually makes sense, because "A" is actually not a number. But what we really want to check is if myVar is exactly of value NaN.
So isNaN() cannot help. Then what should we do instead?
In the light that NaN is the only JavaScript value that is treated unequal to itself, so we can check for its equality to itself using !==
var myVar; // undefined
myVar !== myVar // false
var myVar = "A";
myVar !== myVar // false
var myVar = NaN
myVar !== myVar // true
So to conclude, if it is true that a variable !== itself, then this variable is exactly of value NaN:
function isOfValueNaN(v) {
return v !== v;
}
var myVar = "A";
isNaN(myVar); // true
isOfValueNaN(myVar); // false
To fix the issue where '1.2geoff' becomes parsed, just use the Number() parser instead.
So rather than this:
parseFloat('1.2geoff'); // => 1.2
isNaN(parseFloat('1.2geoff')); // => false
isNaN(parseFloat('.2geoff')); // => false
isNaN(parseFloat('geoff')); // => true
Do this:
Number('1.2geoff'); // => NaN
isNaN(Number('1.2geoff')); // => true
isNaN(Number('.2geoff')); // => true
isNaN(Number('geoff')); // => true
EDIT: I just noticed another issue from this though... false values (and true as a real boolean) passed into Number() return as 0! In which case... parseFloat works every time instead. So fall back to that:
function definitelyNaN (val) {
return isNaN(val && val !== true ? Number(val) : parseFloat(val));
}
And that covers seemingly everything. I benchmarked it at 90% slower than lodash's _.isNaN but then that one doesn't cover all the NaN's:
http://jsperf.com/own-isnan-vs-underscore-lodash-isnan
Just to be clear, mine takes care of the human literal interpretation of something that is "Not a Number" and lodash's takes care of the computer literal interpretation of checking if something is "NaN".
While #chiborg 's answer IS correct, there is more to it that should be noted:
parseFloat('1.2geoff'); // => 1.2
isNaN(parseFloat('1.2geoff')); // => false
isNaN(parseFloat('.2geoff')); // => false
isNaN(parseFloat('geoff')); // => true
Point being, if you're using this method for validation of input, the result will be rather liberal.
So, yes you can use parseFloat(string) (or in the case of full numbers parseInt(string, radix)' and then subsequently wrap that with isNaN(), but be aware of the gotcha with numbers intertwined with additional non-numeric characters.
The rule is:
NaN != NaN
The problem of isNaN() function is that it may return unexpected result in some cases:
isNaN('Hello') //true
isNaN('2005/12/12') //true
isNaN(undefined) //true
isNaN('NaN') //true
isNaN(NaN) //true
isNaN(0 / 0) //true
A better way to check if the value is really NaN is:
function is_nan(value) {
return value != value
}
is_nan(parseFloat("geoff"))
If your environment supports ECMAScript 2015, then you might want to use Number.isNaN to make sure that the value is really NaN.
The problem with isNaN is, if you use that with non-numeric data there are few confusing rules (as per MDN) are applied. For example,
isNaN(NaN); // true
isNaN(undefined); // true
isNaN({}); // true
So, in ECMA Script 2015 supported environments, you might want to use
Number.isNaN(parseFloat('geoff'))
Simple Solution!
REALLY super simple! Here! Have this method!
function isReallyNaN(a) { return a !== a; };
Use as simple as:
if (!isReallyNaN(value)) { return doingStuff; }
See performance test here using this func vs selected answer
Also: See below 1st example for a couple alternate implementations.
Example:
function isReallyNaN(a) { return a !== a; };
var example = {
'NaN': NaN,
'an empty Objet': {},
'a parse to NaN': parseFloat('$5.32'),
'a non-empty Objet': { a: 1, b: 2 },
'an empty Array': [],
'a semi-passed parse': parseInt('5a5'),
'a non-empty Array': [ 'a', 'b', 'c' ],
'Math to NaN': Math.log(-1),
'an undefined object': undefined
}
for (x in example) {
var answer = isReallyNaN(example[x]),
strAnswer = answer.toString();
$("table").append($("<tr />", { "class": strAnswer }).append($("<th />", {
html: x
}), $("<td />", {
html: strAnswer
})))
};
table { border-collapse: collapse; }
th, td { border: 1px solid; padding: 2px 5px; }
.true { color: red; }
.false { color: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table></table>
There are a couple alternate paths you take for implementaion, if you don't want to use an alternately named method, and would like to ensure it's more globally available. Warning These solutions involve altering native objects, and may not be your best solution. Always use caution and be aware that other Libraries you might use may depend on native code or similar alterations.
Alternate Implementation 1: Replace Native isNaN method.
// Extremely simple. Just simply write the method.
window.isNaN = function(a) { return a !==a; }
Alternate Implementation 2: Append to Number Object*Suggested as it is also a poly-fill for ECMA 5 to 6
Number['isNaN'] || (Number.isNaN = function(a) { return a !== a });
// Use as simple as
Number.isNaN(NaN)
Alternate solution test if empty
A simple window method I wrote that test if object is Empty. It's a little different in that it doesn't give if item is "exactly" NaN, but I figured I'd throw this up as it may also be useful when looking for empty items.
/** isEmpty(varried)
* Simple method for testing if item is "empty"
**/
;(function() {
function isEmpty(a) { return (!a || 0 >= a) || ("object" == typeof a && /\{\}|\[(null(,)*)*\]/.test(JSON.stringify(a))); };
window.hasOwnProperty("empty")||(window.empty=isEmpty);
})();
Example:
;(function() {
function isEmpty(a) { return !a || void 0 === a || a !== a || 0 >= a || "object" == typeof a && /\{\}|\[(null(,)*)*\]/.test(JSON.stringify(a)); };
window.hasOwnProperty("empty")||(window.empty=isEmpty);
})();
var example = {
'NaN': NaN,
'an empty Objet': {},
'a parse to NaN': parseFloat('$5.32'),
'a non-empty Objet': { a: 1, b: 2 },
'an empty Array': new Array(),
'an empty Array w/ 9 len': new Array(9),
'a semi-passed parse': parseInt('5a5'),
'a non-empty Array': [ 'a', 'b', 'c' ],
'Math to NaN': Math.log(-1),
'an undefined object': undefined
}
for (x in example) {
var answer = empty(example[x]),
strAnswer = answer.toString();
$("#t1").append(
$("<tr />", { "class": strAnswer }).append(
$("<th />", { html: x }),
$("<td />", { html: strAnswer.toUpperCase() })
)
)
};
function isReallyNaN(a) { return a !== a; };
for(x in example){var answer=isReallyNaN(example[x]),strAnswer=answer.toString();$("#t2").append($("<tr />",{"class":strAnswer}).append($("<th />",{html:x}),$("<td />",{html:strAnswer.toUpperCase()})))};
table { border-collapse: collapse; float: left; }
th, td { border: 1px solid; padding: 2px 5px; }
.true { color: red; }
.false { color: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table id="t1"><thead><tr><th colspan="2">isEmpty()</th></tr></thead><thead><tr><th>Value Type</th><th>Bool Return</th></tr></thead></table>
<table id="t2"><thead><tr><th colspan="2">isReallyNaN()</th></tr></thead><thead><tr><th>Value Type</th><th>Bool Return</th></tr></thead></table>
Extremely Deep Check If Is Empty
This last one goes a bit deep, even checking if an Object is full of blank Objects. I'm sure it has room for improvement and possible pits, but so far, it appears to catch most everything.
function isEmpty(a) {
if (!a || 0 >= a) return !0;
if ("object" == typeof a) {
var b = JSON.stringify(a).replace(/"[^"]*":(0|"0*"|false|null|\{\}|\[(null(,)?)*\]),?/g, '').replace(/"[^"]*":\{\},?/g, '');
if ( /^$|\{\}|\[\]/.test(b) ) return !0;
else if (a instanceof Array) {
b = b.replace(/(0|"0*"|false|null|\{\}|\[(null(,)?)*\]),?/g, '');
if ( /^$|\{\}|\[\]/.test(b) ) return !0;
}
}
return false;
}
window.hasOwnProperty("empty")||(window.empty=isEmpty);
var example = {
'NaN': NaN,
'an empty Objet': {},
'a parse to NaN': parseFloat('$5.32'),
'a non-empty Objet': { a: 1, b: 2 },
'an empty Array': new Array(),
'an empty Array w/ 9 len': new Array(9),
'a semi-passed parse': parseInt('5a5'),
'a non-empty Array': [ 'a', 'b', 'c' ],
'Math to NaN': Math.log(-1),
'an undefined object': undefined,
'Object Full of Empty Items': { 1: '', 2: [], 3: {}, 4: false, 5:new Array(3), 6: NaN, 7: null, 8: void 0, 9: 0, 10: '0', 11: { 6: NaN, 7: null, 8: void 0 } },
'Array Full of Empty Items': ["",[],{},false,[null,null,null],null,null,null,0,"0",{"6":null,"7":null}]
}
for (x in example) {
var answer = empty(example[x]),
strAnswer = answer.toString();
$("#t1").append(
$("<tr />", { "class": strAnswer }).append(
$("<th />", { html: x }),
$("<td />", { html: strAnswer.toUpperCase() })
)
)
};
function isReallyNaN(a) { return a !== a; };
for(x in example){var answer=isReallyNaN(example[x]),strAnswer=answer.toString();$("#t2").append($("<tr />",{"class":strAnswer}).append($("<th />",{html:x}),$("<td />",{html:strAnswer.toUpperCase()})))};
table { border-collapse: collapse; float: left; }
th, td { border: 1px solid; padding: 2px 5px; }
.true { color: red; }
.false { color: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table id="t1"><thead><tr><th colspan="2">isEmpty()</th></tr></thead><thead><tr><th>Value Type</th><th>Bool Return</th></tr></thead></table>
<table id="t2"><thead><tr><th colspan="2">isReallyNaN()</th></tr></thead><thead><tr><th>Value Type</th><th>Bool Return</th></tr></thead></table>
function isNotANumber(n) {
if (typeof n !== 'number') {
return true;
}
return n !== n;
}
I use underscore's isNaN function because in JavaScript:
isNaN(undefined)
-> true
At the least, be aware of that gotcha.
I just want to share another alternative, it's not necessarily better than others here, but I think it's worth looking at:
function customIsNaN(x) { return (typeof x == 'number' && x != 0 && !x); }
The logic behind this is that every number except 0 and NaN are cast to true.
I've done a quick test, and it performs as good as Number.isNaN and as checking against itself for false. All three perform better than isNan
The results
customIsNaN(NaN); // true
customIsNaN(0/0); // true
customIsNaN(+new Date('?')); // true
customIsNaN(0); // false
customIsNaN(false); // false
customIsNaN(null); // false
customIsNaN(undefined); // false
customIsNaN({}); // false
customIsNaN(''); // false
May become useful if you want to avoid the broken isNaN function.
Maybe also this:
function isNaNCustom(value){
return value.toString() === 'NaN' &&
typeof value !== 'string' &&
typeof value === 'number'
}
It seems that isNaN() is not supported in Node.js out of the box.
I worked around with
var value = 1;
if (parseFloat(stringValue)+"" !== "NaN") value = parseFloat(stringValue);
NaN === NaN; // false
Number.NaN === NaN; // false
isNaN(NaN); // true
isNaN(Number.NaN); // true
Equality operator (== and ===) cannot be used to test a value against NaN.
Look at Mozilla Documentation The global NaN property is a value representing Not-A-Numbe
The best way is using 'isNaN()' which is buit-in function to check NaN. All browsers supports the way..
According to IEEE 754, all relationships involving NaN evaluate as false except !=. Thus, for example, (A >= B) = false and (A <= B) = false if A or B or both is/are NaN.
I wrote this answer to another question on StackOverflow where another checks when NaN == null but then it was marked as duplicate so I don't want to waste my job.
Look at Mozilla Developer Network about NaN.
Short answer
Just use distance || 0 when you want to be sure you value is a proper number or isNaN() to check it.
Long answer
The NaN (Not-a-Number) is a weirdo Global Object in javascript frequently returned when some mathematical operation failed.
You wanted to check if NaN == null which results false. Hovewer even NaN == NaN results with false.
A Simple way to find out if variable is NaN is an global function isNaN().
Another is x !== x which is only true when x is NaN. (thanks for remind to #raphael-schweikert)
But why the short answer worked?
Let's find out.
When you call NaN == false the result is false, same with NaN == true.
Somewhere in specifications JavaScript has an record with always false values, which includes:
NaN - Not-a-Number
"" - empty string
false - a boolean false
null - null object
undefined - undefined variables
0 - numerical 0, including +0 and -0
Another solution is mentioned in MDN's parseFloat page
It provides a filter function to do strict parsing
var filterFloat = function (value) {
if(/^(\-|\+)?([0-9]+(\.[0-9]+)?|Infinity)$/
.test(value))
return Number(value);
return NaN;
}
console.log(filterFloat('421')); // 421
console.log(filterFloat('-421')); // -421
console.log(filterFloat('+421')); // 421
console.log(filterFloat('Infinity')); // Infinity
console.log(filterFloat('1.61803398875')); // 1.61803398875
console.log(filterFloat('421e+0')); // NaN
console.log(filterFloat('421hop')); // NaN
console.log(filterFloat('hop1.61803398875')); // NaN
And then you can use isNaN to check if it is NaN
Found another way, just for fun.
function IsActuallyNaN(obj) {
return [obj].includes(NaN);
}
The exact way to check is:
//takes care of boolen, undefined and empty
isNaN(x) || typeof(x) ==='boolean' || typeof(x) !=='undefined' || x!=='' ? 'is really a nan' : 'is a number'
I've created this little function that works like a charm.
Instead of checking for NaN which seems to be counter intuitive, you check for a number. I'm pretty sure I am not the first to do it this way, but I thought i'd share.
function isNum(val){
var absVal = Math.abs(val);
var retval = false;
if((absVal-absVal) == 0){
retval = true
}
return retval;
}
marksyzm's answer works well, but it does not return false for Infinity as Infinity is techinicly not a number.
i came up with a isNumber function that will check if it is a number.
function isNumber(i) {
return !isNaN(i && i !== true ? Number(i) : parseFloat(i)) && [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY].indexOf(i) === -1;
}
console.log(isNumber(Infinity));
console.log(isNumber("asdf"));
console.log(isNumber(1.4));
console.log(isNumber(NaN));
console.log(isNumber(Number.MAX_VALUE));
console.log(isNumber("1.68"));
UPDATE:
i noticed that this code fails for some parameters, so i made it better.
function isNumber(i) {//function for checking if parameter is number
if(!arguments.length) {
throw new SyntaxError("not enough arguments.");
} else if(arguments.length > 1) {
throw new SyntaxError("too many arguments.");
} else if([Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY].indexOf(i) !== -1) {
throw new RangeError("number cannot be \xB1infinity.");
} else if(typeof i === "object" && !(i instanceof RegExp) && !(i instanceof Number) && !(i === null)) {
throw new TypeError("parameter cannot be object/array.");
} else if(i instanceof RegExp) {
throw new TypeError("parameter cannot be RegExp.");
} else if(i == null || i === undefined) {
throw new ReferenceError("parameter is null or undefined.");
} else {
return !isNaN(i && i !== true ? Number(i) : parseFloat(i)) && (i === i);
}
}
console.log(isNumber(Infinity));
console.log(isNumber(this));
console.log(isNumber(/./ig));
console.log(isNumber(null));
alert("1234567890.".indexOf(String.fromCharCode(mycharacter))>-1);
This is not elegant. but after trying isNAN() I arrived at this solution which is another alternative. In this example I also allowed '.' because I am masking for float. You could also reverse this to make sure no numbers are used.
("1234567890".indexOf(String.fromCharCode(mycharacter))==-1)
This is a single character evaluation but you could also loop through a string to check for any numbers.
Number('hello').toString() === 'NaN' // true
Number(undefined).toString() === 'NaN' // true
Number('12345').toString() === 'NaN' // false
// These all evaluate to 0 which is a number
Number('').toString() === 'NaN' // false // 0
Number('0').toString() === 'NaN' // false // 0
Number().toString() === 'NaN' // false // 0
// These all evaluate to 0 and 1 which is a number
Number(false).toString() === 'NaN' // false // 0
Number(true).toString() === 'NaN' // false // 1
Try both in condition
if(isNaN(parseFloat('geoff')) && typeof(parseFloat('geoff')) === "number");
//true
Found this to be useful
// Long-hand const isFalsey = (value) => { if (
value === null ||
value === undefined ||
value === 0 ||
value === false ||
value === NaN ||
value === "" ) {
return true; } return false; };
// Short-hand const
isFalsey = (value) => !value;
I’ve only been trying it in Firefox’s JavaScript console, but neither of the following statements return true:
parseFloat('geoff') == NaN;
parseFloat('geoff') == Number.NaN;
Try this code:
isNaN(parseFloat("geoff"))
For checking whether any value is NaN, instead of just numbers, see here: How do you test for NaN in Javascript?
I just came across this technique in the book Effective JavaScript that is pretty simple:
Since NaN is the only JavaScript value that is treated as unequal to itself, you can always test if a value is NaN by checking it for equality to itself:
var a = NaN;
a !== a; // true
var b = "foo";
b !== b; // false
var c = undefined;
c !== c; // false
var d = {};
d !== d; // false
var e = { valueOf: "foo" };
e !== e; // false
Didn't realize this until #allsyed commented, but this is in the ECMA spec: https://tc39.github.io/ecma262/#sec-isnan-number
Use this code:
isNaN('geoff');
See isNaN() docs on MDN.
alert ( isNaN('abcd')); // alerts true
alert ( isNaN('2.0')); // alerts false
alert ( isNaN(2.0)); // alerts false
As far as a value of type Number is to be tested whether it is a NaN or not, the global function isNaN will do the work
isNaN(any-Number);
For a generic approach which works for all the types in JS, we can use any of the following:
For ECMAScript-5 Users:
#1
if(x !== x) {
console.info('x is NaN.');
}
else {
console.info('x is NOT a NaN.');
}
For people using ECMAScript-6:
#2
Number.isNaN(x);
And For consistency purpose across ECMAScript 5 & 6 both, we can also use this polyfill for Number.isNan
#3
//Polyfill from MDN
Number.isNaN = Number.isNaN || function(value) {
return typeof value === "number" && isNaN(value);
}
// Or
Number.isNaN = Number.isNaN || function(value) {
return value !== value;
}
please check This Answer for more details.
You should use the global isNaN(value) function call, because:
It is supported cross-browser
See isNaN for documentation
Examples:
isNaN('geoff'); // true
isNaN('3'); // false
I hope this will help you.
As of ES6, Object.is(..) is a new utility that can be used to test two values for absolute equality:
var a = 3 / 'bar';
Object.is(a, NaN); // true
NaN is a special value that can't be tested like that. An interesting thing I just wanted to share is this
var nanValue = NaN;
if(nanValue !== nanValue) // Returns true!
alert('nanValue is NaN');
This returns true only for NaN values and Is a safe way of testing. Should definitely be wrapped in a function or atleast commented, because It doesnt make much sense obviously to test if the same variable is not equal to each other, hehe.
NaN in JavaScript stands for "Not A Number", although its type is actually number.
typeof(NaN) // "number"
To check if a variable is of value NaN, we cannot simply use function isNaN(), because isNaN() has the following issue, see below:
var myVar = "A";
isNaN(myVar) // true, although "A" is not really of value NaN
What really happens here is that myVar is implicitly coerced to a number:
var myVar = "A";
isNaN(Number(myVar)) // true. Number(myVar) is NaN here in fact
It actually makes sense, because "A" is actually not a number. But what we really want to check is if myVar is exactly of value NaN.
So isNaN() cannot help. Then what should we do instead?
In the light that NaN is the only JavaScript value that is treated unequal to itself, so we can check for its equality to itself using !==
var myVar; // undefined
myVar !== myVar // false
var myVar = "A";
myVar !== myVar // false
var myVar = NaN
myVar !== myVar // true
So to conclude, if it is true that a variable !== itself, then this variable is exactly of value NaN:
function isOfValueNaN(v) {
return v !== v;
}
var myVar = "A";
isNaN(myVar); // true
isOfValueNaN(myVar); // false
To fix the issue where '1.2geoff' becomes parsed, just use the Number() parser instead.
So rather than this:
parseFloat('1.2geoff'); // => 1.2
isNaN(parseFloat('1.2geoff')); // => false
isNaN(parseFloat('.2geoff')); // => false
isNaN(parseFloat('geoff')); // => true
Do this:
Number('1.2geoff'); // => NaN
isNaN(Number('1.2geoff')); // => true
isNaN(Number('.2geoff')); // => true
isNaN(Number('geoff')); // => true
EDIT: I just noticed another issue from this though... false values (and true as a real boolean) passed into Number() return as 0! In which case... parseFloat works every time instead. So fall back to that:
function definitelyNaN (val) {
return isNaN(val && val !== true ? Number(val) : parseFloat(val));
}
And that covers seemingly everything. I benchmarked it at 90% slower than lodash's _.isNaN but then that one doesn't cover all the NaN's:
http://jsperf.com/own-isnan-vs-underscore-lodash-isnan
Just to be clear, mine takes care of the human literal interpretation of something that is "Not a Number" and lodash's takes care of the computer literal interpretation of checking if something is "NaN".
While #chiborg 's answer IS correct, there is more to it that should be noted:
parseFloat('1.2geoff'); // => 1.2
isNaN(parseFloat('1.2geoff')); // => false
isNaN(parseFloat('.2geoff')); // => false
isNaN(parseFloat('geoff')); // => true
Point being, if you're using this method for validation of input, the result will be rather liberal.
So, yes you can use parseFloat(string) (or in the case of full numbers parseInt(string, radix)' and then subsequently wrap that with isNaN(), but be aware of the gotcha with numbers intertwined with additional non-numeric characters.
The rule is:
NaN != NaN
The problem of isNaN() function is that it may return unexpected result in some cases:
isNaN('Hello') //true
isNaN('2005/12/12') //true
isNaN(undefined) //true
isNaN('NaN') //true
isNaN(NaN) //true
isNaN(0 / 0) //true
A better way to check if the value is really NaN is:
function is_nan(value) {
return value != value
}
is_nan(parseFloat("geoff"))
If your environment supports ECMAScript 2015, then you might want to use Number.isNaN to make sure that the value is really NaN.
The problem with isNaN is, if you use that with non-numeric data there are few confusing rules (as per MDN) are applied. For example,
isNaN(NaN); // true
isNaN(undefined); // true
isNaN({}); // true
So, in ECMA Script 2015 supported environments, you might want to use
Number.isNaN(parseFloat('geoff'))
Simple Solution!
REALLY super simple! Here! Have this method!
function isReallyNaN(a) { return a !== a; };
Use as simple as:
if (!isReallyNaN(value)) { return doingStuff; }
See performance test here using this func vs selected answer
Also: See below 1st example for a couple alternate implementations.
Example:
function isReallyNaN(a) { return a !== a; };
var example = {
'NaN': NaN,
'an empty Objet': {},
'a parse to NaN': parseFloat('$5.32'),
'a non-empty Objet': { a: 1, b: 2 },
'an empty Array': [],
'a semi-passed parse': parseInt('5a5'),
'a non-empty Array': [ 'a', 'b', 'c' ],
'Math to NaN': Math.log(-1),
'an undefined object': undefined
}
for (x in example) {
var answer = isReallyNaN(example[x]),
strAnswer = answer.toString();
$("table").append($("<tr />", { "class": strAnswer }).append($("<th />", {
html: x
}), $("<td />", {
html: strAnswer
})))
};
table { border-collapse: collapse; }
th, td { border: 1px solid; padding: 2px 5px; }
.true { color: red; }
.false { color: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table></table>
There are a couple alternate paths you take for implementaion, if you don't want to use an alternately named method, and would like to ensure it's more globally available. Warning These solutions involve altering native objects, and may not be your best solution. Always use caution and be aware that other Libraries you might use may depend on native code or similar alterations.
Alternate Implementation 1: Replace Native isNaN method.
// Extremely simple. Just simply write the method.
window.isNaN = function(a) { return a !==a; }
Alternate Implementation 2: Append to Number Object*Suggested as it is also a poly-fill for ECMA 5 to 6
Number['isNaN'] || (Number.isNaN = function(a) { return a !== a });
// Use as simple as
Number.isNaN(NaN)
Alternate solution test if empty
A simple window method I wrote that test if object is Empty. It's a little different in that it doesn't give if item is "exactly" NaN, but I figured I'd throw this up as it may also be useful when looking for empty items.
/** isEmpty(varried)
* Simple method for testing if item is "empty"
**/
;(function() {
function isEmpty(a) { return (!a || 0 >= a) || ("object" == typeof a && /\{\}|\[(null(,)*)*\]/.test(JSON.stringify(a))); };
window.hasOwnProperty("empty")||(window.empty=isEmpty);
})();
Example:
;(function() {
function isEmpty(a) { return !a || void 0 === a || a !== a || 0 >= a || "object" == typeof a && /\{\}|\[(null(,)*)*\]/.test(JSON.stringify(a)); };
window.hasOwnProperty("empty")||(window.empty=isEmpty);
})();
var example = {
'NaN': NaN,
'an empty Objet': {},
'a parse to NaN': parseFloat('$5.32'),
'a non-empty Objet': { a: 1, b: 2 },
'an empty Array': new Array(),
'an empty Array w/ 9 len': new Array(9),
'a semi-passed parse': parseInt('5a5'),
'a non-empty Array': [ 'a', 'b', 'c' ],
'Math to NaN': Math.log(-1),
'an undefined object': undefined
}
for (x in example) {
var answer = empty(example[x]),
strAnswer = answer.toString();
$("#t1").append(
$("<tr />", { "class": strAnswer }).append(
$("<th />", { html: x }),
$("<td />", { html: strAnswer.toUpperCase() })
)
)
};
function isReallyNaN(a) { return a !== a; };
for(x in example){var answer=isReallyNaN(example[x]),strAnswer=answer.toString();$("#t2").append($("<tr />",{"class":strAnswer}).append($("<th />",{html:x}),$("<td />",{html:strAnswer.toUpperCase()})))};
table { border-collapse: collapse; float: left; }
th, td { border: 1px solid; padding: 2px 5px; }
.true { color: red; }
.false { color: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table id="t1"><thead><tr><th colspan="2">isEmpty()</th></tr></thead><thead><tr><th>Value Type</th><th>Bool Return</th></tr></thead></table>
<table id="t2"><thead><tr><th colspan="2">isReallyNaN()</th></tr></thead><thead><tr><th>Value Type</th><th>Bool Return</th></tr></thead></table>
Extremely Deep Check If Is Empty
This last one goes a bit deep, even checking if an Object is full of blank Objects. I'm sure it has room for improvement and possible pits, but so far, it appears to catch most everything.
function isEmpty(a) {
if (!a || 0 >= a) return !0;
if ("object" == typeof a) {
var b = JSON.stringify(a).replace(/"[^"]*":(0|"0*"|false|null|\{\}|\[(null(,)?)*\]),?/g, '').replace(/"[^"]*":\{\},?/g, '');
if ( /^$|\{\}|\[\]/.test(b) ) return !0;
else if (a instanceof Array) {
b = b.replace(/(0|"0*"|false|null|\{\}|\[(null(,)?)*\]),?/g, '');
if ( /^$|\{\}|\[\]/.test(b) ) return !0;
}
}
return false;
}
window.hasOwnProperty("empty")||(window.empty=isEmpty);
var example = {
'NaN': NaN,
'an empty Objet': {},
'a parse to NaN': parseFloat('$5.32'),
'a non-empty Objet': { a: 1, b: 2 },
'an empty Array': new Array(),
'an empty Array w/ 9 len': new Array(9),
'a semi-passed parse': parseInt('5a5'),
'a non-empty Array': [ 'a', 'b', 'c' ],
'Math to NaN': Math.log(-1),
'an undefined object': undefined,
'Object Full of Empty Items': { 1: '', 2: [], 3: {}, 4: false, 5:new Array(3), 6: NaN, 7: null, 8: void 0, 9: 0, 10: '0', 11: { 6: NaN, 7: null, 8: void 0 } },
'Array Full of Empty Items': ["",[],{},false,[null,null,null],null,null,null,0,"0",{"6":null,"7":null}]
}
for (x in example) {
var answer = empty(example[x]),
strAnswer = answer.toString();
$("#t1").append(
$("<tr />", { "class": strAnswer }).append(
$("<th />", { html: x }),
$("<td />", { html: strAnswer.toUpperCase() })
)
)
};
function isReallyNaN(a) { return a !== a; };
for(x in example){var answer=isReallyNaN(example[x]),strAnswer=answer.toString();$("#t2").append($("<tr />",{"class":strAnswer}).append($("<th />",{html:x}),$("<td />",{html:strAnswer.toUpperCase()})))};
table { border-collapse: collapse; float: left; }
th, td { border: 1px solid; padding: 2px 5px; }
.true { color: red; }
.false { color: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table id="t1"><thead><tr><th colspan="2">isEmpty()</th></tr></thead><thead><tr><th>Value Type</th><th>Bool Return</th></tr></thead></table>
<table id="t2"><thead><tr><th colspan="2">isReallyNaN()</th></tr></thead><thead><tr><th>Value Type</th><th>Bool Return</th></tr></thead></table>
function isNotANumber(n) {
if (typeof n !== 'number') {
return true;
}
return n !== n;
}
I use underscore's isNaN function because in JavaScript:
isNaN(undefined)
-> true
At the least, be aware of that gotcha.
I just want to share another alternative, it's not necessarily better than others here, but I think it's worth looking at:
function customIsNaN(x) { return (typeof x == 'number' && x != 0 && !x); }
The logic behind this is that every number except 0 and NaN are cast to true.
I've done a quick test, and it performs as good as Number.isNaN and as checking against itself for false. All three perform better than isNan
The results
customIsNaN(NaN); // true
customIsNaN(0/0); // true
customIsNaN(+new Date('?')); // true
customIsNaN(0); // false
customIsNaN(false); // false
customIsNaN(null); // false
customIsNaN(undefined); // false
customIsNaN({}); // false
customIsNaN(''); // false
May become useful if you want to avoid the broken isNaN function.
Maybe also this:
function isNaNCustom(value){
return value.toString() === 'NaN' &&
typeof value !== 'string' &&
typeof value === 'number'
}
It seems that isNaN() is not supported in Node.js out of the box.
I worked around with
var value = 1;
if (parseFloat(stringValue)+"" !== "NaN") value = parseFloat(stringValue);
NaN === NaN; // false
Number.NaN === NaN; // false
isNaN(NaN); // true
isNaN(Number.NaN); // true
Equality operator (== and ===) cannot be used to test a value against NaN.
Look at Mozilla Documentation The global NaN property is a value representing Not-A-Numbe
The best way is using 'isNaN()' which is buit-in function to check NaN. All browsers supports the way..
According to IEEE 754, all relationships involving NaN evaluate as false except !=. Thus, for example, (A >= B) = false and (A <= B) = false if A or B or both is/are NaN.
I wrote this answer to another question on StackOverflow where another checks when NaN == null but then it was marked as duplicate so I don't want to waste my job.
Look at Mozilla Developer Network about NaN.
Short answer
Just use distance || 0 when you want to be sure you value is a proper number or isNaN() to check it.
Long answer
The NaN (Not-a-Number) is a weirdo Global Object in javascript frequently returned when some mathematical operation failed.
You wanted to check if NaN == null which results false. Hovewer even NaN == NaN results with false.
A Simple way to find out if variable is NaN is an global function isNaN().
Another is x !== x which is only true when x is NaN. (thanks for remind to #raphael-schweikert)
But why the short answer worked?
Let's find out.
When you call NaN == false the result is false, same with NaN == true.
Somewhere in specifications JavaScript has an record with always false values, which includes:
NaN - Not-a-Number
"" - empty string
false - a boolean false
null - null object
undefined - undefined variables
0 - numerical 0, including +0 and -0
Another solution is mentioned in MDN's parseFloat page
It provides a filter function to do strict parsing
var filterFloat = function (value) {
if(/^(\-|\+)?([0-9]+(\.[0-9]+)?|Infinity)$/
.test(value))
return Number(value);
return NaN;
}
console.log(filterFloat('421')); // 421
console.log(filterFloat('-421')); // -421
console.log(filterFloat('+421')); // 421
console.log(filterFloat('Infinity')); // Infinity
console.log(filterFloat('1.61803398875')); // 1.61803398875
console.log(filterFloat('421e+0')); // NaN
console.log(filterFloat('421hop')); // NaN
console.log(filterFloat('hop1.61803398875')); // NaN
And then you can use isNaN to check if it is NaN
Found another way, just for fun.
function IsActuallyNaN(obj) {
return [obj].includes(NaN);
}
The exact way to check is:
//takes care of boolen, undefined and empty
isNaN(x) || typeof(x) ==='boolean' || typeof(x) !=='undefined' || x!=='' ? 'is really a nan' : 'is a number'
I've created this little function that works like a charm.
Instead of checking for NaN which seems to be counter intuitive, you check for a number. I'm pretty sure I am not the first to do it this way, but I thought i'd share.
function isNum(val){
var absVal = Math.abs(val);
var retval = false;
if((absVal-absVal) == 0){
retval = true
}
return retval;
}
marksyzm's answer works well, but it does not return false for Infinity as Infinity is techinicly not a number.
i came up with a isNumber function that will check if it is a number.
function isNumber(i) {
return !isNaN(i && i !== true ? Number(i) : parseFloat(i)) && [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY].indexOf(i) === -1;
}
console.log(isNumber(Infinity));
console.log(isNumber("asdf"));
console.log(isNumber(1.4));
console.log(isNumber(NaN));
console.log(isNumber(Number.MAX_VALUE));
console.log(isNumber("1.68"));
UPDATE:
i noticed that this code fails for some parameters, so i made it better.
function isNumber(i) {//function for checking if parameter is number
if(!arguments.length) {
throw new SyntaxError("not enough arguments.");
} else if(arguments.length > 1) {
throw new SyntaxError("too many arguments.");
} else if([Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY].indexOf(i) !== -1) {
throw new RangeError("number cannot be \xB1infinity.");
} else if(typeof i === "object" && !(i instanceof RegExp) && !(i instanceof Number) && !(i === null)) {
throw new TypeError("parameter cannot be object/array.");
} else if(i instanceof RegExp) {
throw new TypeError("parameter cannot be RegExp.");
} else if(i == null || i === undefined) {
throw new ReferenceError("parameter is null or undefined.");
} else {
return !isNaN(i && i !== true ? Number(i) : parseFloat(i)) && (i === i);
}
}
console.log(isNumber(Infinity));
console.log(isNumber(this));
console.log(isNumber(/./ig));
console.log(isNumber(null));
alert("1234567890.".indexOf(String.fromCharCode(mycharacter))>-1);
This is not elegant. but after trying isNAN() I arrived at this solution which is another alternative. In this example I also allowed '.' because I am masking for float. You could also reverse this to make sure no numbers are used.
("1234567890".indexOf(String.fromCharCode(mycharacter))==-1)
This is a single character evaluation but you could also loop through a string to check for any numbers.
Number('hello').toString() === 'NaN' // true
Number(undefined).toString() === 'NaN' // true
Number('12345').toString() === 'NaN' // false
// These all evaluate to 0 which is a number
Number('').toString() === 'NaN' // false // 0
Number('0').toString() === 'NaN' // false // 0
Number().toString() === 'NaN' // false // 0
// These all evaluate to 0 and 1 which is a number
Number(false).toString() === 'NaN' // false // 0
Number(true).toString() === 'NaN' // false // 1
Try both in condition
if(isNaN(parseFloat('geoff')) && typeof(parseFloat('geoff')) === "number");
//true
Found this to be useful
// Long-hand const isFalsey = (value) => { if (
value === null ||
value === undefined ||
value === 0 ||
value === false ||
value === NaN ||
value === "" ) {
return true; } return false; };
// Short-hand const
isFalsey = (value) => !value;
I’ve only been trying it in Firefox’s JavaScript console, but neither of the following statements return true:
parseFloat('geoff') == NaN;
parseFloat('geoff') == Number.NaN;
Try this code:
isNaN(parseFloat("geoff"))
For checking whether any value is NaN, instead of just numbers, see here: How do you test for NaN in Javascript?
I just came across this technique in the book Effective JavaScript that is pretty simple:
Since NaN is the only JavaScript value that is treated as unequal to itself, you can always test if a value is NaN by checking it for equality to itself:
var a = NaN;
a !== a; // true
var b = "foo";
b !== b; // false
var c = undefined;
c !== c; // false
var d = {};
d !== d; // false
var e = { valueOf: "foo" };
e !== e; // false
Didn't realize this until #allsyed commented, but this is in the ECMA spec: https://tc39.github.io/ecma262/#sec-isnan-number
Use this code:
isNaN('geoff');
See isNaN() docs on MDN.
alert ( isNaN('abcd')); // alerts true
alert ( isNaN('2.0')); // alerts false
alert ( isNaN(2.0)); // alerts false
As far as a value of type Number is to be tested whether it is a NaN or not, the global function isNaN will do the work
isNaN(any-Number);
For a generic approach which works for all the types in JS, we can use any of the following:
For ECMAScript-5 Users:
#1
if(x !== x) {
console.info('x is NaN.');
}
else {
console.info('x is NOT a NaN.');
}
For people using ECMAScript-6:
#2
Number.isNaN(x);
And For consistency purpose across ECMAScript 5 & 6 both, we can also use this polyfill for Number.isNan
#3
//Polyfill from MDN
Number.isNaN = Number.isNaN || function(value) {
return typeof value === "number" && isNaN(value);
}
// Or
Number.isNaN = Number.isNaN || function(value) {
return value !== value;
}
please check This Answer for more details.
You should use the global isNaN(value) function call, because:
It is supported cross-browser
See isNaN for documentation
Examples:
isNaN('geoff'); // true
isNaN('3'); // false
I hope this will help you.
As of ES6, Object.is(..) is a new utility that can be used to test two values for absolute equality:
var a = 3 / 'bar';
Object.is(a, NaN); // true
NaN is a special value that can't be tested like that. An interesting thing I just wanted to share is this
var nanValue = NaN;
if(nanValue !== nanValue) // Returns true!
alert('nanValue is NaN');
This returns true only for NaN values and Is a safe way of testing. Should definitely be wrapped in a function or atleast commented, because It doesnt make much sense obviously to test if the same variable is not equal to each other, hehe.
NaN in JavaScript stands for "Not A Number", although its type is actually number.
typeof(NaN) // "number"
To check if a variable is of value NaN, we cannot simply use function isNaN(), because isNaN() has the following issue, see below:
var myVar = "A";
isNaN(myVar) // true, although "A" is not really of value NaN
What really happens here is that myVar is implicitly coerced to a number:
var myVar = "A";
isNaN(Number(myVar)) // true. Number(myVar) is NaN here in fact
It actually makes sense, because "A" is actually not a number. But what we really want to check is if myVar is exactly of value NaN.
So isNaN() cannot help. Then what should we do instead?
In the light that NaN is the only JavaScript value that is treated unequal to itself, so we can check for its equality to itself using !==
var myVar; // undefined
myVar !== myVar // false
var myVar = "A";
myVar !== myVar // false
var myVar = NaN
myVar !== myVar // true
So to conclude, if it is true that a variable !== itself, then this variable is exactly of value NaN:
function isOfValueNaN(v) {
return v !== v;
}
var myVar = "A";
isNaN(myVar); // true
isOfValueNaN(myVar); // false
To fix the issue where '1.2geoff' becomes parsed, just use the Number() parser instead.
So rather than this:
parseFloat('1.2geoff'); // => 1.2
isNaN(parseFloat('1.2geoff')); // => false
isNaN(parseFloat('.2geoff')); // => false
isNaN(parseFloat('geoff')); // => true
Do this:
Number('1.2geoff'); // => NaN
isNaN(Number('1.2geoff')); // => true
isNaN(Number('.2geoff')); // => true
isNaN(Number('geoff')); // => true
EDIT: I just noticed another issue from this though... false values (and true as a real boolean) passed into Number() return as 0! In which case... parseFloat works every time instead. So fall back to that:
function definitelyNaN (val) {
return isNaN(val && val !== true ? Number(val) : parseFloat(val));
}
And that covers seemingly everything. I benchmarked it at 90% slower than lodash's _.isNaN but then that one doesn't cover all the NaN's:
http://jsperf.com/own-isnan-vs-underscore-lodash-isnan
Just to be clear, mine takes care of the human literal interpretation of something that is "Not a Number" and lodash's takes care of the computer literal interpretation of checking if something is "NaN".
While #chiborg 's answer IS correct, there is more to it that should be noted:
parseFloat('1.2geoff'); // => 1.2
isNaN(parseFloat('1.2geoff')); // => false
isNaN(parseFloat('.2geoff')); // => false
isNaN(parseFloat('geoff')); // => true
Point being, if you're using this method for validation of input, the result will be rather liberal.
So, yes you can use parseFloat(string) (or in the case of full numbers parseInt(string, radix)' and then subsequently wrap that with isNaN(), but be aware of the gotcha with numbers intertwined with additional non-numeric characters.
The rule is:
NaN != NaN
The problem of isNaN() function is that it may return unexpected result in some cases:
isNaN('Hello') //true
isNaN('2005/12/12') //true
isNaN(undefined) //true
isNaN('NaN') //true
isNaN(NaN) //true
isNaN(0 / 0) //true
A better way to check if the value is really NaN is:
function is_nan(value) {
return value != value
}
is_nan(parseFloat("geoff"))
If your environment supports ECMAScript 2015, then you might want to use Number.isNaN to make sure that the value is really NaN.
The problem with isNaN is, if you use that with non-numeric data there are few confusing rules (as per MDN) are applied. For example,
isNaN(NaN); // true
isNaN(undefined); // true
isNaN({}); // true
So, in ECMA Script 2015 supported environments, you might want to use
Number.isNaN(parseFloat('geoff'))
Simple Solution!
REALLY super simple! Here! Have this method!
function isReallyNaN(a) { return a !== a; };
Use as simple as:
if (!isReallyNaN(value)) { return doingStuff; }
See performance test here using this func vs selected answer
Also: See below 1st example for a couple alternate implementations.
Example:
function isReallyNaN(a) { return a !== a; };
var example = {
'NaN': NaN,
'an empty Objet': {},
'a parse to NaN': parseFloat('$5.32'),
'a non-empty Objet': { a: 1, b: 2 },
'an empty Array': [],
'a semi-passed parse': parseInt('5a5'),
'a non-empty Array': [ 'a', 'b', 'c' ],
'Math to NaN': Math.log(-1),
'an undefined object': undefined
}
for (x in example) {
var answer = isReallyNaN(example[x]),
strAnswer = answer.toString();
$("table").append($("<tr />", { "class": strAnswer }).append($("<th />", {
html: x
}), $("<td />", {
html: strAnswer
})))
};
table { border-collapse: collapse; }
th, td { border: 1px solid; padding: 2px 5px; }
.true { color: red; }
.false { color: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table></table>
There are a couple alternate paths you take for implementaion, if you don't want to use an alternately named method, and would like to ensure it's more globally available. Warning These solutions involve altering native objects, and may not be your best solution. Always use caution and be aware that other Libraries you might use may depend on native code or similar alterations.
Alternate Implementation 1: Replace Native isNaN method.
// Extremely simple. Just simply write the method.
window.isNaN = function(a) { return a !==a; }
Alternate Implementation 2: Append to Number Object*Suggested as it is also a poly-fill for ECMA 5 to 6
Number['isNaN'] || (Number.isNaN = function(a) { return a !== a });
// Use as simple as
Number.isNaN(NaN)
Alternate solution test if empty
A simple window method I wrote that test if object is Empty. It's a little different in that it doesn't give if item is "exactly" NaN, but I figured I'd throw this up as it may also be useful when looking for empty items.
/** isEmpty(varried)
* Simple method for testing if item is "empty"
**/
;(function() {
function isEmpty(a) { return (!a || 0 >= a) || ("object" == typeof a && /\{\}|\[(null(,)*)*\]/.test(JSON.stringify(a))); };
window.hasOwnProperty("empty")||(window.empty=isEmpty);
})();
Example:
;(function() {
function isEmpty(a) { return !a || void 0 === a || a !== a || 0 >= a || "object" == typeof a && /\{\}|\[(null(,)*)*\]/.test(JSON.stringify(a)); };
window.hasOwnProperty("empty")||(window.empty=isEmpty);
})();
var example = {
'NaN': NaN,
'an empty Objet': {},
'a parse to NaN': parseFloat('$5.32'),
'a non-empty Objet': { a: 1, b: 2 },
'an empty Array': new Array(),
'an empty Array w/ 9 len': new Array(9),
'a semi-passed parse': parseInt('5a5'),
'a non-empty Array': [ 'a', 'b', 'c' ],
'Math to NaN': Math.log(-1),
'an undefined object': undefined
}
for (x in example) {
var answer = empty(example[x]),
strAnswer = answer.toString();
$("#t1").append(
$("<tr />", { "class": strAnswer }).append(
$("<th />", { html: x }),
$("<td />", { html: strAnswer.toUpperCase() })
)
)
};
function isReallyNaN(a) { return a !== a; };
for(x in example){var answer=isReallyNaN(example[x]),strAnswer=answer.toString();$("#t2").append($("<tr />",{"class":strAnswer}).append($("<th />",{html:x}),$("<td />",{html:strAnswer.toUpperCase()})))};
table { border-collapse: collapse; float: left; }
th, td { border: 1px solid; padding: 2px 5px; }
.true { color: red; }
.false { color: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table id="t1"><thead><tr><th colspan="2">isEmpty()</th></tr></thead><thead><tr><th>Value Type</th><th>Bool Return</th></tr></thead></table>
<table id="t2"><thead><tr><th colspan="2">isReallyNaN()</th></tr></thead><thead><tr><th>Value Type</th><th>Bool Return</th></tr></thead></table>
Extremely Deep Check If Is Empty
This last one goes a bit deep, even checking if an Object is full of blank Objects. I'm sure it has room for improvement and possible pits, but so far, it appears to catch most everything.
function isEmpty(a) {
if (!a || 0 >= a) return !0;
if ("object" == typeof a) {
var b = JSON.stringify(a).replace(/"[^"]*":(0|"0*"|false|null|\{\}|\[(null(,)?)*\]),?/g, '').replace(/"[^"]*":\{\},?/g, '');
if ( /^$|\{\}|\[\]/.test(b) ) return !0;
else if (a instanceof Array) {
b = b.replace(/(0|"0*"|false|null|\{\}|\[(null(,)?)*\]),?/g, '');
if ( /^$|\{\}|\[\]/.test(b) ) return !0;
}
}
return false;
}
window.hasOwnProperty("empty")||(window.empty=isEmpty);
var example = {
'NaN': NaN,
'an empty Objet': {},
'a parse to NaN': parseFloat('$5.32'),
'a non-empty Objet': { a: 1, b: 2 },
'an empty Array': new Array(),
'an empty Array w/ 9 len': new Array(9),
'a semi-passed parse': parseInt('5a5'),
'a non-empty Array': [ 'a', 'b', 'c' ],
'Math to NaN': Math.log(-1),
'an undefined object': undefined,
'Object Full of Empty Items': { 1: '', 2: [], 3: {}, 4: false, 5:new Array(3), 6: NaN, 7: null, 8: void 0, 9: 0, 10: '0', 11: { 6: NaN, 7: null, 8: void 0 } },
'Array Full of Empty Items': ["",[],{},false,[null,null,null],null,null,null,0,"0",{"6":null,"7":null}]
}
for (x in example) {
var answer = empty(example[x]),
strAnswer = answer.toString();
$("#t1").append(
$("<tr />", { "class": strAnswer }).append(
$("<th />", { html: x }),
$("<td />", { html: strAnswer.toUpperCase() })
)
)
};
function isReallyNaN(a) { return a !== a; };
for(x in example){var answer=isReallyNaN(example[x]),strAnswer=answer.toString();$("#t2").append($("<tr />",{"class":strAnswer}).append($("<th />",{html:x}),$("<td />",{html:strAnswer.toUpperCase()})))};
table { border-collapse: collapse; float: left; }
th, td { border: 1px solid; padding: 2px 5px; }
.true { color: red; }
.false { color: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table id="t1"><thead><tr><th colspan="2">isEmpty()</th></tr></thead><thead><tr><th>Value Type</th><th>Bool Return</th></tr></thead></table>
<table id="t2"><thead><tr><th colspan="2">isReallyNaN()</th></tr></thead><thead><tr><th>Value Type</th><th>Bool Return</th></tr></thead></table>
function isNotANumber(n) {
if (typeof n !== 'number') {
return true;
}
return n !== n;
}
I use underscore's isNaN function because in JavaScript:
isNaN(undefined)
-> true
At the least, be aware of that gotcha.
I just want to share another alternative, it's not necessarily better than others here, but I think it's worth looking at:
function customIsNaN(x) { return (typeof x == 'number' && x != 0 && !x); }
The logic behind this is that every number except 0 and NaN are cast to true.
I've done a quick test, and it performs as good as Number.isNaN and as checking against itself for false. All three perform better than isNan
The results
customIsNaN(NaN); // true
customIsNaN(0/0); // true
customIsNaN(+new Date('?')); // true
customIsNaN(0); // false
customIsNaN(false); // false
customIsNaN(null); // false
customIsNaN(undefined); // false
customIsNaN({}); // false
customIsNaN(''); // false
May become useful if you want to avoid the broken isNaN function.
Maybe also this:
function isNaNCustom(value){
return value.toString() === 'NaN' &&
typeof value !== 'string' &&
typeof value === 'number'
}
It seems that isNaN() is not supported in Node.js out of the box.
I worked around with
var value = 1;
if (parseFloat(stringValue)+"" !== "NaN") value = parseFloat(stringValue);
NaN === NaN; // false
Number.NaN === NaN; // false
isNaN(NaN); // true
isNaN(Number.NaN); // true
Equality operator (== and ===) cannot be used to test a value against NaN.
Look at Mozilla Documentation The global NaN property is a value representing Not-A-Numbe
The best way is using 'isNaN()' which is buit-in function to check NaN. All browsers supports the way..
According to IEEE 754, all relationships involving NaN evaluate as false except !=. Thus, for example, (A >= B) = false and (A <= B) = false if A or B or both is/are NaN.
I wrote this answer to another question on StackOverflow where another checks when NaN == null but then it was marked as duplicate so I don't want to waste my job.
Look at Mozilla Developer Network about NaN.
Short answer
Just use distance || 0 when you want to be sure you value is a proper number or isNaN() to check it.
Long answer
The NaN (Not-a-Number) is a weirdo Global Object in javascript frequently returned when some mathematical operation failed.
You wanted to check if NaN == null which results false. Hovewer even NaN == NaN results with false.
A Simple way to find out if variable is NaN is an global function isNaN().
Another is x !== x which is only true when x is NaN. (thanks for remind to #raphael-schweikert)
But why the short answer worked?
Let's find out.
When you call NaN == false the result is false, same with NaN == true.
Somewhere in specifications JavaScript has an record with always false values, which includes:
NaN - Not-a-Number
"" - empty string
false - a boolean false
null - null object
undefined - undefined variables
0 - numerical 0, including +0 and -0
Another solution is mentioned in MDN's parseFloat page
It provides a filter function to do strict parsing
var filterFloat = function (value) {
if(/^(\-|\+)?([0-9]+(\.[0-9]+)?|Infinity)$/
.test(value))
return Number(value);
return NaN;
}
console.log(filterFloat('421')); // 421
console.log(filterFloat('-421')); // -421
console.log(filterFloat('+421')); // 421
console.log(filterFloat('Infinity')); // Infinity
console.log(filterFloat('1.61803398875')); // 1.61803398875
console.log(filterFloat('421e+0')); // NaN
console.log(filterFloat('421hop')); // NaN
console.log(filterFloat('hop1.61803398875')); // NaN
And then you can use isNaN to check if it is NaN
Found another way, just for fun.
function IsActuallyNaN(obj) {
return [obj].includes(NaN);
}
The exact way to check is:
//takes care of boolen, undefined and empty
isNaN(x) || typeof(x) ==='boolean' || typeof(x) !=='undefined' || x!=='' ? 'is really a nan' : 'is a number'
I've created this little function that works like a charm.
Instead of checking for NaN which seems to be counter intuitive, you check for a number. I'm pretty sure I am not the first to do it this way, but I thought i'd share.
function isNum(val){
var absVal = Math.abs(val);
var retval = false;
if((absVal-absVal) == 0){
retval = true
}
return retval;
}
marksyzm's answer works well, but it does not return false for Infinity as Infinity is techinicly not a number.
i came up with a isNumber function that will check if it is a number.
function isNumber(i) {
return !isNaN(i && i !== true ? Number(i) : parseFloat(i)) && [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY].indexOf(i) === -1;
}
console.log(isNumber(Infinity));
console.log(isNumber("asdf"));
console.log(isNumber(1.4));
console.log(isNumber(NaN));
console.log(isNumber(Number.MAX_VALUE));
console.log(isNumber("1.68"));
UPDATE:
i noticed that this code fails for some parameters, so i made it better.
function isNumber(i) {//function for checking if parameter is number
if(!arguments.length) {
throw new SyntaxError("not enough arguments.");
} else if(arguments.length > 1) {
throw new SyntaxError("too many arguments.");
} else if([Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY].indexOf(i) !== -1) {
throw new RangeError("number cannot be \xB1infinity.");
} else if(typeof i === "object" && !(i instanceof RegExp) && !(i instanceof Number) && !(i === null)) {
throw new TypeError("parameter cannot be object/array.");
} else if(i instanceof RegExp) {
throw new TypeError("parameter cannot be RegExp.");
} else if(i == null || i === undefined) {
throw new ReferenceError("parameter is null or undefined.");
} else {
return !isNaN(i && i !== true ? Number(i) : parseFloat(i)) && (i === i);
}
}
console.log(isNumber(Infinity));
console.log(isNumber(this));
console.log(isNumber(/./ig));
console.log(isNumber(null));
alert("1234567890.".indexOf(String.fromCharCode(mycharacter))>-1);
This is not elegant. but after trying isNAN() I arrived at this solution which is another alternative. In this example I also allowed '.' because I am masking for float. You could also reverse this to make sure no numbers are used.
("1234567890".indexOf(String.fromCharCode(mycharacter))==-1)
This is a single character evaluation but you could also loop through a string to check for any numbers.
Number('hello').toString() === 'NaN' // true
Number(undefined).toString() === 'NaN' // true
Number('12345').toString() === 'NaN' // false
// These all evaluate to 0 which is a number
Number('').toString() === 'NaN' // false // 0
Number('0').toString() === 'NaN' // false // 0
Number().toString() === 'NaN' // false // 0
// These all evaluate to 0 and 1 which is a number
Number(false).toString() === 'NaN' // false // 0
Number(true).toString() === 'NaN' // false // 1
Try both in condition
if(isNaN(parseFloat('geoff')) && typeof(parseFloat('geoff')) === "number");
//true
Found this to be useful
// Long-hand const isFalsey = (value) => { if (
value === null ||
value === undefined ||
value === 0 ||
value === false ||
value === NaN ||
value === "" ) {
return true; } return false; };
// Short-hand const
isFalsey = (value) => !value;
I’ve only been trying it in Firefox’s JavaScript console, but neither of the following statements return true:
parseFloat('geoff') == NaN;
parseFloat('geoff') == Number.NaN;
Try this code:
isNaN(parseFloat("geoff"))
For checking whether any value is NaN, instead of just numbers, see here: How do you test for NaN in Javascript?
I just came across this technique in the book Effective JavaScript that is pretty simple:
Since NaN is the only JavaScript value that is treated as unequal to itself, you can always test if a value is NaN by checking it for equality to itself:
var a = NaN;
a !== a; // true
var b = "foo";
b !== b; // false
var c = undefined;
c !== c; // false
var d = {};
d !== d; // false
var e = { valueOf: "foo" };
e !== e; // false
Didn't realize this until #allsyed commented, but this is in the ECMA spec: https://tc39.github.io/ecma262/#sec-isnan-number
Use this code:
isNaN('geoff');
See isNaN() docs on MDN.
alert ( isNaN('abcd')); // alerts true
alert ( isNaN('2.0')); // alerts false
alert ( isNaN(2.0)); // alerts false
As far as a value of type Number is to be tested whether it is a NaN or not, the global function isNaN will do the work
isNaN(any-Number);
For a generic approach which works for all the types in JS, we can use any of the following:
For ECMAScript-5 Users:
#1
if(x !== x) {
console.info('x is NaN.');
}
else {
console.info('x is NOT a NaN.');
}
For people using ECMAScript-6:
#2
Number.isNaN(x);
And For consistency purpose across ECMAScript 5 & 6 both, we can also use this polyfill for Number.isNan
#3
//Polyfill from MDN
Number.isNaN = Number.isNaN || function(value) {
return typeof value === "number" && isNaN(value);
}
// Or
Number.isNaN = Number.isNaN || function(value) {
return value !== value;
}
please check This Answer for more details.
You should use the global isNaN(value) function call, because:
It is supported cross-browser
See isNaN for documentation
Examples:
isNaN('geoff'); // true
isNaN('3'); // false
I hope this will help you.
As of ES6, Object.is(..) is a new utility that can be used to test two values for absolute equality:
var a = 3 / 'bar';
Object.is(a, NaN); // true
NaN is a special value that can't be tested like that. An interesting thing I just wanted to share is this
var nanValue = NaN;
if(nanValue !== nanValue) // Returns true!
alert('nanValue is NaN');
This returns true only for NaN values and Is a safe way of testing. Should definitely be wrapped in a function or atleast commented, because It doesnt make much sense obviously to test if the same variable is not equal to each other, hehe.
NaN in JavaScript stands for "Not A Number", although its type is actually number.
typeof(NaN) // "number"
To check if a variable is of value NaN, we cannot simply use function isNaN(), because isNaN() has the following issue, see below:
var myVar = "A";
isNaN(myVar) // true, although "A" is not really of value NaN
What really happens here is that myVar is implicitly coerced to a number:
var myVar = "A";
isNaN(Number(myVar)) // true. Number(myVar) is NaN here in fact
It actually makes sense, because "A" is actually not a number. But what we really want to check is if myVar is exactly of value NaN.
So isNaN() cannot help. Then what should we do instead?
In the light that NaN is the only JavaScript value that is treated unequal to itself, so we can check for its equality to itself using !==
var myVar; // undefined
myVar !== myVar // false
var myVar = "A";
myVar !== myVar // false
var myVar = NaN
myVar !== myVar // true
So to conclude, if it is true that a variable !== itself, then this variable is exactly of value NaN:
function isOfValueNaN(v) {
return v !== v;
}
var myVar = "A";
isNaN(myVar); // true
isOfValueNaN(myVar); // false
To fix the issue where '1.2geoff' becomes parsed, just use the Number() parser instead.
So rather than this:
parseFloat('1.2geoff'); // => 1.2
isNaN(parseFloat('1.2geoff')); // => false
isNaN(parseFloat('.2geoff')); // => false
isNaN(parseFloat('geoff')); // => true
Do this:
Number('1.2geoff'); // => NaN
isNaN(Number('1.2geoff')); // => true
isNaN(Number('.2geoff')); // => true
isNaN(Number('geoff')); // => true
EDIT: I just noticed another issue from this though... false values (and true as a real boolean) passed into Number() return as 0! In which case... parseFloat works every time instead. So fall back to that:
function definitelyNaN (val) {
return isNaN(val && val !== true ? Number(val) : parseFloat(val));
}
And that covers seemingly everything. I benchmarked it at 90% slower than lodash's _.isNaN but then that one doesn't cover all the NaN's:
http://jsperf.com/own-isnan-vs-underscore-lodash-isnan
Just to be clear, mine takes care of the human literal interpretation of something that is "Not a Number" and lodash's takes care of the computer literal interpretation of checking if something is "NaN".
While #chiborg 's answer IS correct, there is more to it that should be noted:
parseFloat('1.2geoff'); // => 1.2
isNaN(parseFloat('1.2geoff')); // => false
isNaN(parseFloat('.2geoff')); // => false
isNaN(parseFloat('geoff')); // => true
Point being, if you're using this method for validation of input, the result will be rather liberal.
So, yes you can use parseFloat(string) (or in the case of full numbers parseInt(string, radix)' and then subsequently wrap that with isNaN(), but be aware of the gotcha with numbers intertwined with additional non-numeric characters.
The rule is:
NaN != NaN
The problem of isNaN() function is that it may return unexpected result in some cases:
isNaN('Hello') //true
isNaN('2005/12/12') //true
isNaN(undefined) //true
isNaN('NaN') //true
isNaN(NaN) //true
isNaN(0 / 0) //true
A better way to check if the value is really NaN is:
function is_nan(value) {
return value != value
}
is_nan(parseFloat("geoff"))
If your environment supports ECMAScript 2015, then you might want to use Number.isNaN to make sure that the value is really NaN.
The problem with isNaN is, if you use that with non-numeric data there are few confusing rules (as per MDN) are applied. For example,
isNaN(NaN); // true
isNaN(undefined); // true
isNaN({}); // true
So, in ECMA Script 2015 supported environments, you might want to use
Number.isNaN(parseFloat('geoff'))
Simple Solution!
REALLY super simple! Here! Have this method!
function isReallyNaN(a) { return a !== a; };
Use as simple as:
if (!isReallyNaN(value)) { return doingStuff; }
See performance test here using this func vs selected answer
Also: See below 1st example for a couple alternate implementations.
Example:
function isReallyNaN(a) { return a !== a; };
var example = {
'NaN': NaN,
'an empty Objet': {},
'a parse to NaN': parseFloat('$5.32'),
'a non-empty Objet': { a: 1, b: 2 },
'an empty Array': [],
'a semi-passed parse': parseInt('5a5'),
'a non-empty Array': [ 'a', 'b', 'c' ],
'Math to NaN': Math.log(-1),
'an undefined object': undefined
}
for (x in example) {
var answer = isReallyNaN(example[x]),
strAnswer = answer.toString();
$("table").append($("<tr />", { "class": strAnswer }).append($("<th />", {
html: x
}), $("<td />", {
html: strAnswer
})))
};
table { border-collapse: collapse; }
th, td { border: 1px solid; padding: 2px 5px; }
.true { color: red; }
.false { color: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table></table>
There are a couple alternate paths you take for implementaion, if you don't want to use an alternately named method, and would like to ensure it's more globally available. Warning These solutions involve altering native objects, and may not be your best solution. Always use caution and be aware that other Libraries you might use may depend on native code or similar alterations.
Alternate Implementation 1: Replace Native isNaN method.
// Extremely simple. Just simply write the method.
window.isNaN = function(a) { return a !==a; }
Alternate Implementation 2: Append to Number Object*Suggested as it is also a poly-fill for ECMA 5 to 6
Number['isNaN'] || (Number.isNaN = function(a) { return a !== a });
// Use as simple as
Number.isNaN(NaN)
Alternate solution test if empty
A simple window method I wrote that test if object is Empty. It's a little different in that it doesn't give if item is "exactly" NaN, but I figured I'd throw this up as it may also be useful when looking for empty items.
/** isEmpty(varried)
* Simple method for testing if item is "empty"
**/
;(function() {
function isEmpty(a) { return (!a || 0 >= a) || ("object" == typeof a && /\{\}|\[(null(,)*)*\]/.test(JSON.stringify(a))); };
window.hasOwnProperty("empty")||(window.empty=isEmpty);
})();
Example:
;(function() {
function isEmpty(a) { return !a || void 0 === a || a !== a || 0 >= a || "object" == typeof a && /\{\}|\[(null(,)*)*\]/.test(JSON.stringify(a)); };
window.hasOwnProperty("empty")||(window.empty=isEmpty);
})();
var example = {
'NaN': NaN,
'an empty Objet': {},
'a parse to NaN': parseFloat('$5.32'),
'a non-empty Objet': { a: 1, b: 2 },
'an empty Array': new Array(),
'an empty Array w/ 9 len': new Array(9),
'a semi-passed parse': parseInt('5a5'),
'a non-empty Array': [ 'a', 'b', 'c' ],
'Math to NaN': Math.log(-1),
'an undefined object': undefined
}
for (x in example) {
var answer = empty(example[x]),
strAnswer = answer.toString();
$("#t1").append(
$("<tr />", { "class": strAnswer }).append(
$("<th />", { html: x }),
$("<td />", { html: strAnswer.toUpperCase() })
)
)
};
function isReallyNaN(a) { return a !== a; };
for(x in example){var answer=isReallyNaN(example[x]),strAnswer=answer.toString();$("#t2").append($("<tr />",{"class":strAnswer}).append($("<th />",{html:x}),$("<td />",{html:strAnswer.toUpperCase()})))};
table { border-collapse: collapse; float: left; }
th, td { border: 1px solid; padding: 2px 5px; }
.true { color: red; }
.false { color: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table id="t1"><thead><tr><th colspan="2">isEmpty()</th></tr></thead><thead><tr><th>Value Type</th><th>Bool Return</th></tr></thead></table>
<table id="t2"><thead><tr><th colspan="2">isReallyNaN()</th></tr></thead><thead><tr><th>Value Type</th><th>Bool Return</th></tr></thead></table>
Extremely Deep Check If Is Empty
This last one goes a bit deep, even checking if an Object is full of blank Objects. I'm sure it has room for improvement and possible pits, but so far, it appears to catch most everything.
function isEmpty(a) {
if (!a || 0 >= a) return !0;
if ("object" == typeof a) {
var b = JSON.stringify(a).replace(/"[^"]*":(0|"0*"|false|null|\{\}|\[(null(,)?)*\]),?/g, '').replace(/"[^"]*":\{\},?/g, '');
if ( /^$|\{\}|\[\]/.test(b) ) return !0;
else if (a instanceof Array) {
b = b.replace(/(0|"0*"|false|null|\{\}|\[(null(,)?)*\]),?/g, '');
if ( /^$|\{\}|\[\]/.test(b) ) return !0;
}
}
return false;
}
window.hasOwnProperty("empty")||(window.empty=isEmpty);
var example = {
'NaN': NaN,
'an empty Objet': {},
'a parse to NaN': parseFloat('$5.32'),
'a non-empty Objet': { a: 1, b: 2 },
'an empty Array': new Array(),
'an empty Array w/ 9 len': new Array(9),
'a semi-passed parse': parseInt('5a5'),
'a non-empty Array': [ 'a', 'b', 'c' ],
'Math to NaN': Math.log(-1),
'an undefined object': undefined,
'Object Full of Empty Items': { 1: '', 2: [], 3: {}, 4: false, 5:new Array(3), 6: NaN, 7: null, 8: void 0, 9: 0, 10: '0', 11: { 6: NaN, 7: null, 8: void 0 } },
'Array Full of Empty Items': ["",[],{},false,[null,null,null],null,null,null,0,"0",{"6":null,"7":null}]
}
for (x in example) {
var answer = empty(example[x]),
strAnswer = answer.toString();
$("#t1").append(
$("<tr />", { "class": strAnswer }).append(
$("<th />", { html: x }),
$("<td />", { html: strAnswer.toUpperCase() })
)
)
};
function isReallyNaN(a) { return a !== a; };
for(x in example){var answer=isReallyNaN(example[x]),strAnswer=answer.toString();$("#t2").append($("<tr />",{"class":strAnswer}).append($("<th />",{html:x}),$("<td />",{html:strAnswer.toUpperCase()})))};
table { border-collapse: collapse; float: left; }
th, td { border: 1px solid; padding: 2px 5px; }
.true { color: red; }
.false { color: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table id="t1"><thead><tr><th colspan="2">isEmpty()</th></tr></thead><thead><tr><th>Value Type</th><th>Bool Return</th></tr></thead></table>
<table id="t2"><thead><tr><th colspan="2">isReallyNaN()</th></tr></thead><thead><tr><th>Value Type</th><th>Bool Return</th></tr></thead></table>
function isNotANumber(n) {
if (typeof n !== 'number') {
return true;
}
return n !== n;
}
I use underscore's isNaN function because in JavaScript:
isNaN(undefined)
-> true
At the least, be aware of that gotcha.
I just want to share another alternative, it's not necessarily better than others here, but I think it's worth looking at:
function customIsNaN(x) { return (typeof x == 'number' && x != 0 && !x); }
The logic behind this is that every number except 0 and NaN are cast to true.
I've done a quick test, and it performs as good as Number.isNaN and as checking against itself for false. All three perform better than isNan
The results
customIsNaN(NaN); // true
customIsNaN(0/0); // true
customIsNaN(+new Date('?')); // true
customIsNaN(0); // false
customIsNaN(false); // false
customIsNaN(null); // false
customIsNaN(undefined); // false
customIsNaN({}); // false
customIsNaN(''); // false
May become useful if you want to avoid the broken isNaN function.
Maybe also this:
function isNaNCustom(value){
return value.toString() === 'NaN' &&
typeof value !== 'string' &&
typeof value === 'number'
}
It seems that isNaN() is not supported in Node.js out of the box.
I worked around with
var value = 1;
if (parseFloat(stringValue)+"" !== "NaN") value = parseFloat(stringValue);
NaN === NaN; // false
Number.NaN === NaN; // false
isNaN(NaN); // true
isNaN(Number.NaN); // true
Equality operator (== and ===) cannot be used to test a value against NaN.
Look at Mozilla Documentation The global NaN property is a value representing Not-A-Numbe
The best way is using 'isNaN()' which is buit-in function to check NaN. All browsers supports the way..
According to IEEE 754, all relationships involving NaN evaluate as false except !=. Thus, for example, (A >= B) = false and (A <= B) = false if A or B or both is/are NaN.
I wrote this answer to another question on StackOverflow where another checks when NaN == null but then it was marked as duplicate so I don't want to waste my job.
Look at Mozilla Developer Network about NaN.
Short answer
Just use distance || 0 when you want to be sure you value is a proper number or isNaN() to check it.
Long answer
The NaN (Not-a-Number) is a weirdo Global Object in javascript frequently returned when some mathematical operation failed.
You wanted to check if NaN == null which results false. Hovewer even NaN == NaN results with false.
A Simple way to find out if variable is NaN is an global function isNaN().
Another is x !== x which is only true when x is NaN. (thanks for remind to #raphael-schweikert)
But why the short answer worked?
Let's find out.
When you call NaN == false the result is false, same with NaN == true.
Somewhere in specifications JavaScript has an record with always false values, which includes:
NaN - Not-a-Number
"" - empty string
false - a boolean false
null - null object
undefined - undefined variables
0 - numerical 0, including +0 and -0
Another solution is mentioned in MDN's parseFloat page
It provides a filter function to do strict parsing
var filterFloat = function (value) {
if(/^(\-|\+)?([0-9]+(\.[0-9]+)?|Infinity)$/
.test(value))
return Number(value);
return NaN;
}
console.log(filterFloat('421')); // 421
console.log(filterFloat('-421')); // -421
console.log(filterFloat('+421')); // 421
console.log(filterFloat('Infinity')); // Infinity
console.log(filterFloat('1.61803398875')); // 1.61803398875
console.log(filterFloat('421e+0')); // NaN
console.log(filterFloat('421hop')); // NaN
console.log(filterFloat('hop1.61803398875')); // NaN
And then you can use isNaN to check if it is NaN
Found another way, just for fun.
function IsActuallyNaN(obj) {
return [obj].includes(NaN);
}
The exact way to check is:
//takes care of boolen, undefined and empty
isNaN(x) || typeof(x) ==='boolean' || typeof(x) !=='undefined' || x!=='' ? 'is really a nan' : 'is a number'
I've created this little function that works like a charm.
Instead of checking for NaN which seems to be counter intuitive, you check for a number. I'm pretty sure I am not the first to do it this way, but I thought i'd share.
function isNum(val){
var absVal = Math.abs(val);
var retval = false;
if((absVal-absVal) == 0){
retval = true
}
return retval;
}
marksyzm's answer works well, but it does not return false for Infinity as Infinity is techinicly not a number.
i came up with a isNumber function that will check if it is a number.
function isNumber(i) {
return !isNaN(i && i !== true ? Number(i) : parseFloat(i)) && [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY].indexOf(i) === -1;
}
console.log(isNumber(Infinity));
console.log(isNumber("asdf"));
console.log(isNumber(1.4));
console.log(isNumber(NaN));
console.log(isNumber(Number.MAX_VALUE));
console.log(isNumber("1.68"));
UPDATE:
i noticed that this code fails for some parameters, so i made it better.
function isNumber(i) {//function for checking if parameter is number
if(!arguments.length) {
throw new SyntaxError("not enough arguments.");
} else if(arguments.length > 1) {
throw new SyntaxError("too many arguments.");
} else if([Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY].indexOf(i) !== -1) {
throw new RangeError("number cannot be \xB1infinity.");
} else if(typeof i === "object" && !(i instanceof RegExp) && !(i instanceof Number) && !(i === null)) {
throw new TypeError("parameter cannot be object/array.");
} else if(i instanceof RegExp) {
throw new TypeError("parameter cannot be RegExp.");
} else if(i == null || i === undefined) {
throw new ReferenceError("parameter is null or undefined.");
} else {
return !isNaN(i && i !== true ? Number(i) : parseFloat(i)) && (i === i);
}
}
console.log(isNumber(Infinity));
console.log(isNumber(this));
console.log(isNumber(/./ig));
console.log(isNumber(null));
alert("1234567890.".indexOf(String.fromCharCode(mycharacter))>-1);
This is not elegant. but after trying isNAN() I arrived at this solution which is another alternative. In this example I also allowed '.' because I am masking for float. You could also reverse this to make sure no numbers are used.
("1234567890".indexOf(String.fromCharCode(mycharacter))==-1)
This is a single character evaluation but you could also loop through a string to check for any numbers.
Number('hello').toString() === 'NaN' // true
Number(undefined).toString() === 'NaN' // true
Number('12345').toString() === 'NaN' // false
// These all evaluate to 0 which is a number
Number('').toString() === 'NaN' // false // 0
Number('0').toString() === 'NaN' // false // 0
Number().toString() === 'NaN' // false // 0
// These all evaluate to 0 and 1 which is a number
Number(false).toString() === 'NaN' // false // 0
Number(true).toString() === 'NaN' // false // 1
Try both in condition
if(isNaN(parseFloat('geoff')) && typeof(parseFloat('geoff')) === "number");
//true
Found this to be useful
// Long-hand const isFalsey = (value) => { if (
value === null ||
value === undefined ||
value === 0 ||
value === false ||
value === NaN ||
value === "" ) {
return true; } return false; };
// Short-hand const
isFalsey = (value) => !value;
I need to disable/enable a button depending in on the value of some radio groups. These radios are populated by some groovy code becasue I'm using grails, a framework for groovy, that is a superset of java. Well that explanation was to say that the values of the radios are defined as booleans, which is just natural because they correspond to yes/no answers.
Now, to disable/enable this button I use some javascript, but it goes bananas with boolean values. As the title states, on some point I do a logical and between a variable that holds false and another variable that holds true
Here is the peice of problematic code:
var actual = true;
$('.requerido input:radio:checked').each(function() {
console.log("actual: " + actual);
console.log("value: " + this.value);
console.log("actual and value: " + (actual && this.value));
actual = actual && this.value;
console.log("actual: " + actual);
});
As you can see I use the console.log for debugging, and this is what throws at some point:
actual: true
value: true
actual and value: true
actual: true
actual: true
value: false
actual and value: false
actual: false
actual: false
value: true
actual and value: true
actual: true
So true && false == false, but false && true == true ? Note that the values have no quotes, so they are boolean values (I'm debugging using the Chrome console which represent strings inside double quotes, so you can distinguish between true and "true").
Any ideas?
Also, doing a manual comparison like var x = true && false always works as expected, is juts with variables that the problem is present.
The this.value from your checked radio button input is not actually a boolean it is a string. The comparison of strings and boolean values can cause issues like this. It is one of the reasons why it is considered best practise is to use === for comparison.
See this SO Question for full details; JavaScript === vs == : Does it matter which “equal” operator I use?
Note that the && does the following:
Returns expr1 if it can be converted to false; otherwise, returns
expr2.
source
So in cases like:
var truish=true;//interchangeable with anything different than 0,"",false,null,undefined,NaN
var falsish=null;//interchangeable with 0,"",false,null,undefined,NaN
alert(truish&&falsish);//null (falsish was returned)
The returned value isn't necessarily a boolean, a solution to this would be to force a boolean !(x&&y)
So my guess is that something like this is happening
if you are trying to calculate with logic operators, remember:
var result = true && "false";// always results (string) "false"
var result = true && "true";// always results (string) "true"
var result = false && "true";// always results (boolean) false
var result = false && "false";// always results (boolean) false
var result = "true" && true;// always results (boolean) true
var result = "true" && false;// always results (boolean) false
var result = "false" && true;// always results (boolean) true
var result = "false" && false;// always results (boolean) false
var result = "true" && "true";// always results (string)"true"
var result = "true" && "false";// always results (string) "false"
var result = "false" && "true";// always results (string) "true"
var result = "false" && "false";// always results (string) "false"
because:
javascript judge the first operand, if true it will return the second operand, or else return false; it just like:
var first = true
var second = "false";
if (first) {
result = second;
} else {
result = false;
}
or
result = first ? second : false;
this is the way javascript logic operator actually works.
you must perform strict comparison between different variable types:
result = true && (value==="false");
strings not empty is equal to (boolean)true, even "false".
and remember that html element attributes are "String"s
This must have to do something with (one of) the values of your radio controls, because in plain javascript this evaluates as expected:
function boolx(tf,val){
var test = tf && val;
console.log([tf,val,tf && val,test]);
}
tf(true,false); //=> [true,false,false,false]
tf(false,true); //=> [false,true,false,false]
Maybe an explicit conversion of this.value helps, because this.value is actually a string:
var actual = true;
$('.requerido input:radio:checked').each(function() {
var val = /true/i.test(this.value);
console.log("actual: " + actual);
console.log("value: " + val);
console.log("actual and value: " + (actual && val));
actual = actual && val;
console.log("actual: " + actual);
});
Try a bitwise and & vice &&. The later would be appropriate in a conditional comparison, but not in assigning a value to a variable.
Is this really what you want to do? :
actual = actual && this.value;
That's the same as:
if (actual) {
actual = this.value;
}
actual is always true as defined in your code, so actual would be this.value and not a boolean.