How do I check if a variable is an integer in JavaScript, and throw an alert if it isn't? I tried this, but it doesn't work:
<html>
<head>
<script type="text/javascript">
var data = 22;
alert(NaN(data));
</script>
</head>
</html>
That depends, do you also want to cast strings as potential integers as well?
This will do:
function isInt(value) {
return !isNaN(value) &&
parseInt(Number(value)) == value &&
!isNaN(parseInt(value, 10));
}
With Bitwise operations
Simple parse and check
function isInt(value) {
var x = parseFloat(value);
return !isNaN(value) && (x | 0) === x;
}
Short-circuiting, and saving a parse operation:
function isInt(value) {
if (isNaN(value)) {
return false;
}
var x = parseFloat(value);
return (x | 0) === x;
}
Or perhaps both in one shot:
function isInt(value) {
return !isNaN(value) && (function(x) { return (x | 0) === x; })(parseFloat(value))
}
Tests:
isInt(42) // true
isInt("42") // true
isInt(4e2) // true
isInt("4e2") // true
isInt(" 1 ") // true
isInt("") // false
isInt(" ") // false
isInt(42.1) // false
isInt("1a") // false
isInt("4e2a") // false
isInt(null) // false
isInt(undefined) // false
isInt(NaN) // false
Here's the fiddle: http://jsfiddle.net/opfyrqwp/28/
Performance
Testing reveals that the short-circuiting solution has the best performance (ops/sec).
// Short-circuiting, and saving a parse operation
function isInt(value) {
var x;
if (isNaN(value)) {
return false;
}
x = parseFloat(value);
return (x | 0) === x;
}
Here is a benchmark:
http://jsben.ch/#/htLVw
If you fancy a shorter, obtuse form of short circuiting:
function isInt(value) {
var x;
return isNaN(value) ? !1 : (x = parseFloat(value), (0 | x) === x);
}
Of course, I'd suggest letting the minifier take care of that.
Use the === operator (strict equality) as below,
if (data === parseInt(data, 10))
alert("data is integer")
else
alert("data is not an integer")
Number.isInteger() seems to be the way to go.
MDN has also provided the following polyfill for browsers not supporting Number.isInteger(), mainly all versions of IE.
Link to MDN page
Number.isInteger = Number.isInteger || function(value) {
return typeof value === "number" &&
isFinite(value) &&
Math.floor(value) === value;
};
Assuming you don't know anything about the variable in question, you should take this approach:
if(typeof data === 'number') {
var remainder = (data % 1);
if(remainder === 0) {
// yes, it is an integer
}
else if(isNaN(remainder)) {
// no, data is either: NaN, Infinity, or -Infinity
}
else {
// no, it is a float (still a number though)
}
}
else {
// no way, it is not even a number
}
To put it simply:
if(typeof data==='number' && (data%1)===0) {
// data is an integer
}
You could check if the number has a remainder:
var data = 22;
if(data % 1 === 0){
// yes it's an integer.
}
Mind you, if your input could also be text and you want to check first it is not, then you can check the type first:
var data = 22;
if(typeof data === 'number'){
// yes it is numeric
if(data % 1 === 0){
// yes it's an integer.
}
}
You can use a simple regular expression:
function isInt(value) {
var er = /^-?[0-9]+$/;
return er.test(value);
}
In ES6 2 new methods are added for Number Object.
In it Number.isInteger() method returns true if the argument is an integer, otherwise returns false.
Important Note: The method will also return true for floating point numbers that can be represented as integer. Eg: 5.0 (as it is exactly equal to 5 )
Example usage :
Number.isInteger(0); // true
Number.isInteger(1); // true
Number.isInteger(-100000); // true
Number.isInteger(99999999999999999999999); // true
Number.isInteger(0.1); // false
Number.isInteger(Math.PI); // false
Number.isInteger(NaN); // false
Number.isInteger(Infinity); // false
Number.isInteger(-Infinity); // false
Number.isInteger('10'); // false
Number.isInteger(true); // false
Number.isInteger(false); // false
Number.isInteger([1]); // false
Number.isInteger(5.0); // true
Number.isInteger(5.000000000000001); // false
Number.isInteger(5.0000000000000001); // true
First off, NaN is a "number" (yes I know it's weird, just roll with it), and not a "function".
You need to check both if the type of the variable is a number, and to check for integer I would use modulus.
alert(typeof data === 'number' && data%1 == 0);
Be careful while using
num % 1
empty string ('') or boolean (true or false) will return as integer. You might not want to do that
false % 1 // true
'' % 1 //true
Number.isInteger(data)
Number.isInteger(22); //true
Number.isInteger(22.2); //false
Number.isInteger('22'); //false
build in function in the browser. Dosnt support older browsers
Alternatives:
Math.round(num)=== num
However, Math.round() also will fail for empty string and boolean
To check if integer like poster wants:
if (+data===parseInt(data)) {return true} else {return false}
notice + in front of data (converts string to number), and === for exact.
Here are examples:
data=10
+data===parseInt(data)
true
data="10"
+data===parseInt(data)
true
data="10.2"
+data===parseInt(data)
false
The simplest and cleanest pre-ECMAScript-6 solution (which is also sufficiently robust to return false even if a non-numeric value such as a string or null is passed to the function) would be the following:
function isInteger(x) { return (x^0) === x; }
The following solution would also work, although not as elegant as the one above:
function isInteger(x) { return Math.round(x) === x; }
Note that Math.ceil() or Math.floor() could be used equally well (instead of Math.round()) in the above implementation.
Or alternatively:
function isInteger(x) { return (typeof x === 'number') && (x % 1 === 0); }
One fairly common incorrect solution is the following:
function isInteger(x) { return parseInt(x, 10) === x; }
While this parseInt-based approach will work well for many values of x, once x becomes quite large, it will fail to work properly. The problem is that parseInt() coerces its first parameter to a string before parsing digits. Therefore, once the number becomes sufficiently large, its string representation will be presented in exponential form (e.g., 1e+21). Accordingly, parseInt() will then try to parse 1e+21, but will stop parsing when it reaches the e character and will therefore return a value of 1. Observe:
> String(1000000000000000000000)
'1e+21'
> parseInt(1000000000000000000000, 10)
1
> parseInt(1000000000000000000000, 10) === 1000000000000000000000
false
Why hasnt anyone mentioned Number.isInteger() ?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
Works perfectly for me and solves the issue with the NaN beginning a number.
if(Number.isInteger(Number(data))){
//-----
}
Check if the variable is equal to that same variable rounded to an integer, like this:
if(Math.round(data) != data) {
alert("Variable is not an integer!");
}
ECMA-262 6.0 (ES6) standard include Number.isInteger function.
In order to add support for old browser I highly recommend using strong and community supported solution from:
https://github.com/paulmillr/es6-shim
which is pure ES6 JS polyfills library.
Note that this lib require es5-shim, just follow README.md.
The Accepted answer not worked for me as i needed to check for int/float and alphabet. so try this at will work for both int/float and alphabet check
function is_int(value){
if( (parseInt(value) % 1 === 0 )){
return true;
}else{
return false;
}
}
usage
is_int(44); // true
is_int("44"); // true
is_int(44.55); // true
is_int("44.55"); // true
is_int("aaa"); // false
You could use this function:
function isInteger(value) {
return (value == parseInt(value));
}
It will return true even if the value is a string containing an integer value.
So, the results will be:
alert(isInteger(1)); // true
alert(isInteger(1.2)); // false
alert(isInteger("1")); // true
alert(isInteger("1.2")); // false
alert(isInteger("abc")); // false
Use the | operator:
(5.3 | 0) === 5.3 // => false
(5.0 | 0) === 5.0 // => true
So, a test function might look like this:
var isInteger = function (value) {
if (typeof value !== 'number') {
return false;
}
if ((value | 0) !== value) {
return false;
}
return true;
};
Number.isInteger() is the best way if your browser support it, if not, I think there are so many ways to go:
function isInt1(value){
return (value^0) === value
}
or:
function isInt2(value){
return (typeof value === 'number') && (value % 1 === 0);
}
or:
function isInt3(value){
return parseInt(value, 10) === value;
}
or:
function isInt4(value){
return Math.round(value) === value;
}
now we can test the results:
var value = 1
isInt1(value) // return true
isInt2(value) // return true
isInt3(value) // return true
isInt4(value) // return true
var value = 1.1
isInt1(value) // return false
isInt2(value) // return false
isInt3(value) // return false
isInt4(value) // return false
var value = 1000000000000000000
isInt1(value) // return false
isInt2(value) // return true
isInt3(value) // return false
isInt4(value) // return true
var value = undefined
isInt1(value) // return false
isInt2(value) // return false
isInt3(value) // return false
isInt4(value) // return false
var value = '1' //number as string
isInt1(value) // return false
isInt2(value) // return false
isInt3(value) // return false
isInt4(value) // return false
So, all of these methods are works, but when the number is very big, parseInt and ^ operator would not works well.
You could tryNumber.isInteger(Number(value)) if value might be an integer in string form e.g var value = "23" and you want this to evaluate to true. Avoid trying Number.isInteger(parseInt(value)) because this won't always return the correct value. e.g if var value = "23abc" and you use the parseInt implementation, it would still return true.
But if you want strictly integer values then probably Number.isInteger(value) should do the trick.
var x = 1.5;
if(!isNaN(x)){
console.log('Number');
if(x % 1 == 0){
console.log('Integer');
}
}else {
console.log('not a number');
}
What about large integers (bigint)?
Most of these answers fail on large integers (253 and larger): Bitwise tests(e.g. (x | 0) === x), testing typeof x === 'number', regular int functions (e.g. parseInt), regular arithmetics fail on large integers. This can be resolved by using BigInt.
I've compiled several answers into one snippet to show the results. Most outright fail with large integers, while others work, except when passed the type BigInt (e.g. 1n). I've not included duplicate answers and have also left out any answers that allow decimals or don't attempt to test type)
// these all fail
n = 1000000000000000000000000000000
b = 1n
// These all fail on large integers
//https://stackoverflow.com/a/14636652/3600709
console.log('fail',1,n === parseInt(n, 10))
//https://stackoverflow.com/a/14794066/3600709
console.log('fail',2,!isNaN(n) && parseInt(Number(n)) == n && !isNaN(parseInt(n, 10)))
console.log('fail',2,!isNaN(n) && (parseFloat(n) | 0) === parseFloat(n))
console.log('fail',2,!isNaN(n) && (function(x) { return (x | 0) === x; })(parseFloat(n)))
//https://stackoverflow.com/a/21742529/3600709
console.log('fail',3,n == ~~n)
//https://stackoverflow.com/a/28211631/3600709
console.log('fail',4,!isNaN(n) && parseInt(n) == parseFloat(n))
//https://stackoverflow.com/a/41854178/3600709
console.log('fail',5,String(parseInt(n, 10)) === String(n))
// These ones work for integers, but not BigInt types (e.g. 1n)
//https://stackoverflow.com/a/14636725/3600709
console.log('partial',1,typeof n==='number' && (n%1)===0) // this one works
console.log('partial',1,typeof b==='number' && (b%1)===0) // this one fails
//https://stackoverflow.com/a/27424770/3600709
console.log('partial',2,Number.isInteger(n)) // this one works
console.log('partial',2,Number.isInteger(b)) // this one fails
//https://stackoverflow.com/a/14636638/3600709
console.log('partial',3,n % 1 === 0)
console.log('partial',3,b % 1 === 0) // gives uncaught type on BigInt
Checking type
If you actually want to test the incoming value's type to ensure it's an integer, use this instead:
function isInt(value) {
try {
BigInt(value)
return !['string','object','boolean'].includes(typeof value)
} catch(e) {
return false
}
}
function isInt(value) {
try {
BigInt(value)
return !['string','object','boolean'].includes(typeof value)
} catch(e) {
return false
}
}
console.log('--- should be false')
console.log(isInt(undefined))
console.log(isInt(''))
console.log(isInt(null))
console.log(isInt({}))
console.log(isInt([]))
console.log(isInt(1.1e-1))
console.log(isInt(1.1))
console.log(isInt(true))
console.log(isInt(NaN))
console.log(isInt('1'))
console.log(isInt(function(){}))
console.log(isInt(Infinity))
console.log('--- should be true')
console.log(isInt(10))
console.log(isInt(0x11))
console.log(isInt(0))
console.log(isInt(-10000))
console.log(isInt(100000000000000000000000000000000000000))
console.log(isInt(1n))
Without checking type
If you don't care if the incoming type is actually boolean, string, etc. converted into a number, then just use the following:
function isInt(value) {
try {
BigInt(value)
return true
} catch(e) {
return false
}
}
function isInt(value) {
try {
BigInt(value)
return true
} catch(e) {
return false
}
}
console.log('--- should be false')
console.log(isInt(undefined))
console.log(isInt(null))
console.log(isInt({}))
console.log(isInt(1.1e-1))
console.log(isInt(1.1))
console.log(isInt(NaN))
console.log(isInt(function(){}))
console.log(isInt(Infinity))
console.log('--- should be true')
console.log(isInt(10))
console.log(isInt(0x11))
console.log(isInt(0))
console.log(isInt(-10000))
console.log(isInt(100000000000000000000000000000000000000))
console.log(isInt(1n))
// gets converted to number
console.log(isInt(''))
console.log(isInt([]))
console.log(isInt(true))
console.log(isInt('1'))
My approach:
a >= 1e+21 → Only pass for very large numbers. This will cover all cases for sure, unlike other solutions which has been provided in this discussion.
a === (a|0) → if the given function's argument is exactly the same (===) as the bitwise-transformed value, it means that the argument is an integer.
a|0 → return 0 for any value of a that isn't a number, and if a is indeed a number, it will strip away anything after the decimal point, so 1.0001 will become 1
const isInteger = n => n >= 1e+21 ? true : n === (n|0);
// tests:
[
[1, true],
[1000000000000000000000, true],
[4e2, true],
[Infinity, true],
[1.0, true],
[1.0000000000001, false],
[0.1, false],
["0", false],
["1", false],
["1.1", false],
[NaN, false],
[[], false],
[{}, false],
[true, false],
[false, false],
[null, false],
[undefined, false],
].forEach(([test, expected]) =>
console.log(
isInteger(test) === expected,
typeof test,
test
)
)
Besides, Number.isInteger(). Maybe Number.isSafeInteger() is another option here by using the ES6-specified.
To polyfill Number.isSafeInteger(..) in pre-ES6 browsers:
Number.isSafeInteger = Number.isSafeInteger || function(num) {
return typeof num === "number" &&
isFinite(num) &&
Math.floor(num) === num &&
Math.abs( num ) <= Number.MAX_SAFE_INTEGER;
};
you can also try it this way
var data = 22;
if (Number.isInteger(data)) {
console.log("integer");
}else{
console.log("not an integer");
}
or
if (data === parseInt(data, 10)){
console.log("integer");
}else{
console.log("not an integer");
}
Just try this:
let number = 5;
if (Number.isInteger(number)) {
//do something
}
The 'accepted' answer is wrong (as some comments below point out).
this modification can make it work:
if (data.toString() === parseInt(data, 10).toString())
alert("data is a valid integer")
else
alert("data is not a valid integer")
You can use regexp for this:
function isInteger(n) {
return (typeof n == 'number' && /^-?\d+$/.test(n+''));
}
From http://www.toptal.com/javascript/interview-questions:
function isInteger(x) { return (x^0) === x; }
Found it to be the best way to do this.
function isInteger(argument) { return argument == ~~argument; }
Usage:
isInteger(1); // true<br>
isInteger(0.1); // false<br>
isInteger("1"); // true<br>
isInteger("0.1"); // false<br>
or:
function isInteger(argument) { return argument == argument + 0 && argument == ~~argument; }
Usage:
isInteger(1); // true<br>
isInteger(0.1); // false<br>
isInteger("1"); // false<br>
isInteger("0.1"); // false<br>
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;
Is there a universal JavaScript function that checks that a variable has a value and ensures that it's not undefined or null? I've got this code, but I'm not sure if it covers all cases:
function isEmpty(val){
return (val === undefined || val == null || val.length <= 0) ? true : false;
}
You can just check if the variable has a truthy value or not. That means
if (value) {
// do something..
}
will evaluate to true if value is not:
null
undefined
NaN
empty string ("")
0
false
The above list represents all possible falsy values in ECMA-/Javascript. Find it in the specification at the ToBoolean section.
Furthermore, if you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator. For instance
if (typeof foo !== 'undefined') {
// foo could get resolved and it's defined
}
If you can be sure that a variable is declared at least, you should directly check if it has a truthy value like shown above.
The verbose method to check if value is undefined or null is:
return value === undefined || value === null;
You can also use the == operator but this expects one to know all the rules:
return value == null; // also returns true if value is undefined
function isEmpty(value){
return (value == null || value.length === 0);
}
This will return true for
undefined // Because undefined == null
null
[]
""
and zero argument functions since a function's length is the number of declared parameters it takes.
To disallow the latter category, you might want to just check for blank strings
function isEmpty(value){
return (value == null || value === '');
}
Null or whitespace
function isEmpty(value){
return (value == null || value.trim().length === 0);
}
This is the safest check and I haven't seen it posted here exactly like that:
if (typeof value !== 'undefined' && value) {
//deal with value'
};
It will cover cases where value was never defined, and also any of these:
null
undefined (value of undefined is not the same as a parameter that was never defined)
0
"" (empty string)
false
NaN
Edited: Changed to strict equality (!==) because it's the norm by now ;)
You may find the following function useful:
function typeOf(obj) {
return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}
Or in ES7 (comment if further improvements)
function typeOf(obj) {
const { toString } = Object.prototype;
const stringified = obj::toString();
const type = stringified.split(' ')[1].slice(0, -1);
return type.toLowerCase();
}
Results:
typeOf(); //undefined
typeOf(null); //null
typeOf(NaN); //number
typeOf(5); //number
typeOf({}); //object
typeOf([]); //array
typeOf(''); //string
typeOf(function () {}); //function
typeOf(/a/) //regexp
typeOf(new Date()) //date
typeOf(new WeakMap()) //weakmap
typeOf(new Map()) //map
"Note that the bind operator (::) is not part of ES2016 (ES7) nor any later edition of the ECMAScript standard at all. It's currently a stage 0 (strawman) proposal for being introduced to the language." – Simon Kjellberg. the author wishes to add his support for this beautiful proposal to receive royal ascension.
A solution I like a lot:
Let's define that a blank variable is null, or undefined, or if it has length, it is zero, or if it is an object, it has no keys:
function isEmpty (value) {
return (
// null or undefined
(value == null) ||
// has length and it's zero
(value.hasOwnProperty('length') && value.length === 0) ||
// is an Object and has no keys
(value.constructor === Object && Object.keys(value).length === 0)
)
}
Returns:
true: undefined, null, "", [], {}
false: true, false, 1, 0, -1, "foo", [1, 2, 3], { foo: 1 }
This condition check
if (!!foo) {
//foo is defined
}
is all you need.
Take a look at the new ECMAScript Nullish coalescing operator
You can think of this feature - the ?? operator - as a way to “fall back” to a default value when dealing with null or undefined.
let x = foo ?? bar();
Again, the above code is equivalent to the following.
let x = (foo !== null && foo !== undefined) ? foo : bar();
The first answer with best rating is wrong. If value is undefined it will throw an exception in modern browsers. You have to use:
if (typeof(value) !== "undefined" && value)
or
if (typeof value !== "undefined" && value)
! check for empty strings (""), null, undefined, false and the number 0 and NaN. Say, if a string is empty var name = "" then console.log(!name) returns true.
function isEmpty(val){
return !val;
}
this function will return true if val is empty, null, undefined, false, the number 0 or NaN.
OR
According to your problem domain you can just use like !val or !!val.
You are a bit overdoing it. To check if a variable is not given a value, you would only need to check against undefined and null.
function isEmpty(value){
return (typeof value === "undefined" || value === null);
}
This is assuming 0, "", and objects(even empty object and array) are valid "values".
Vacuousness
I don't recommend trying to define or use a function which computes whether any value in the whole world is empty. What does it really mean to be "empty"? If I have let human = { name: 'bob', stomach: 'empty' }, should isEmpty(human) return true? If I have let reg = new RegExp('');, should isEmpty(reg) return true? What about isEmpty([ null, null, null, null ]) - this list only contains emptiness, so is the list itself empty? I want to put forward here some notes on "vacuousness" (an intentionally obscure word, to avoid pre-existing associations) in javascript - and I want to argue that "vacuousness" in javascript values should never be dealt with generically.
Truthiness/Falsiness
For deciding how to determine the "vacuousness" of values, we need to accomodate javascript's inbuilt, inherent sense of whether values are "truthy" or "falsy". Naturally, null and undefined are both "falsy". Less naturally, the number 0 (and no other number except NaN) is also "falsy". Least naturally: '' is falsy, but [] and {} (and new Set(), and new Map()) are truthy - although they all seem equally vacuous!
Null vs Undefined
There is also some discussion concerning null vs undefined - do we really need both in order to express vacuousness in our programs? I personally avoid ever having undefined appear in my code. I always use null to signify "vacuousness". Again, though, we need to accomodate javascript's inherent sense of how null and undefined differ:
Trying to access a non-existent property gives undefined
Omitting a parameter when calling a function results in that parameter receiving undefined:
let f = a => a;
console.log(f('hi'));
console.log(f());
Parameters with default values receive the default only when given undefined, not null:
let f = (v='hello') => v;
console.log(f(null));
console.log(f(undefined));
To me, null is an explicit signifier of vacuousness; "something that could have been filled in was intentionally left blank".
Really undefined is a necessary complication that allows some js features to exist, but in my opinion it should always be left behind the scenes; not interacted with directly. We can think of undefined as, for example, javascript's mechanic for implementing default function arguments. If you refrain from supplying an argument to a function it will receive a value of undefined instead. And a default value will be applied to a function argument if that argument was initially set to undefined. In this case undefined is the linchpin of default function arguments, but it stays in the background: we can achieve default argument functionality without ever referring to undefined:
This is a bad implementation of default arguments as it interacts directly with undefined:
let fnWithDefaults = arg => {
if (arg === undefined) arg = 'default';
...
};
This is a good implementation:
let fnWithDefaults = (arg='default') => { ... };
This is a bad way to accept the default argument:
fnWithDefaults(undefined);
Simply do this instead:
fnWithDefaults();
By the way: do you have a function with multiple arguments, and you want to provide some arguments while accepting defaults for others?
E.g.:
let fnWithDefaults = (a=1, b=2, c=3, d=4) => console.log(a, b, c, d);
If you want to provide values for a and d and accepts defaults for the others what to do? This seems wrong:
fnWithDefaults(10, undefined, undefined, 40);
The answer is: refactor fnWithDefaults to accept a single object:
let fnWithDefaults = ({ a=1, b=2, c=3, d=4 }={}) => console.log(a, b, c, d);
fnWithDefaults({ a: 10, d: 40 }); // Now this looks really nice! (And never talks about "undefined")
Non-generic Vacuousness
I believe that vacuousness should never be dealt with in a generic fashion. We should instead always have the rigour to get more information about our data before determining if it is vacuous - I mainly do this by checking what type of data I'm dealing with:
let isType = (value, Cls) => {
// Intentional use of loose comparison operator detects `null`
// and `undefined`, and nothing else!
return value != null && Object.getPrototypeOf(value).constructor === Cls;
};
Note that this function ignores inheritance - it expects value to be a direct instance of Cls, and not an instance of a subclass of Cls. I avoid instanceof for two main reasons:
([] instanceof Object) === true ("An Array is an Object")
('' instanceof String) === false ("A String is not a String")
Note that Object.getPrototypeOf is used to avoid an (obscure) edge-case such as let v = { constructor: String }; The isType function still returns correctly for isType(v, String) (false), and isType(v, Object) (true).
Overall, I recommend using this isType function along with these tips:
Minimize the amount of code processing values of unknown type. E.g., for let v = JSON.parse(someRawValue);, our v variable is now of unknown type. As early as possible, we should limit our possibilities. The best way to do this can be by requiring a particular type: e.g. if (!isType(v, Array)) throw new Error('Expected Array'); - this is a really quick and expressive way to remove the generic nature of v, and ensure it's always an Array. Sometimes, though, we need to allow v to be of multiple types. In those cases, we should create blocks of code where v is no longer generic, as early as possible:
if (isType(v, String)) {
/* v isn't generic in this block - It's a String! */
} else if (isType(v, Number)) {
/* v isn't generic in this block - It's a Number! */
} else if (isType(v, Array)) {
/* v isn't generic in this block - it's an Array! */
} else {
throw new Error('Expected String, Number, or Array');
}
Always use "whitelists" for validation. If you require a value to be, e.g., a String, Number, or Array, check for those 3 "white" possibilities, and throw an Error if none of the 3 are satisfied. We should be able to see that checking for "black" possibilities isn't very useful: Say we write if (v === null) throw new Error('Null value rejected'); - this is great for ensuring that null values don't make it through, but if a value does make it through, we still know hardly anything about it. A value v which passes this null-check is still VERY generic - it's anything but null! Blacklists hardly dispell generic-ness.
Unless a value is null, never consider "a vacuous value". Instead, consider "an X which is vacuous". Essentially, never consider doing anything like if (isEmpty(val)) { /* ... */ } - no matter how that isEmpty function is implemented (I don't want to know...), it isn't meaningful! And it's way too generic! Vacuousness should only be calculated with knowledge of val's type. Vacuousness-checks should look like this:
"A string, with no chars":
if (isType(val, String) && val.length === 0) ...
"An Object, with 0 props": if (isType(val, Object) && Object.entries(val).length === 0) ...
"A number, equal or less than zero": if (isType(val, Number) && val <= 0) ...
"An Array, with no items": if (isType(val, Array) && val.length === 0) ...
The only exception is when null is used to signify certain functionality. In this case it's meaningful to say: "A vacuous value": if (val === null) ...
The probably shortest answer is
val==null || val==''
if you change rigth side to val==='' then empty array will give false. Proof
function isEmpty(val){
return val==null || val==''
}
// ------------
// TEST
// ------------
var log = (name,val) => console.log(`${name} -> ${isEmpty(val)}`);
log('null', null);
log('undefined', undefined);
log('NaN', NaN);
log('""', "");
log('{}', {});
log('[]', []);
log('[1]', [1]);
log('[0]', [0]);
log('[[]]', [[]]);
log('true', true);
log('false', false);
log('"true"', "true");
log('"false"', "false");
log('Infinity', Infinity);
log('-Infinity', -Infinity);
log('1', 1);
log('0', 0);
log('-1', -1);
log('"1"', "1");
log('"0"', "0");
log('"-1"', "-1");
// "void 0" case
console.log('---\n"true" is:', true);
console.log('"void 0" is:', void 0);
log(void 0,void 0); // "void 0" is "undefined" - so we should get here TRUE
More details about == (source here)
BONUS: Reason why === is more clear than ==
To write clear and easy
understandable code, use explicite list of accepted values
val===undefined || val===null || val===''|| (Array.isArray(val) && val.length===0)
function isEmpty(val){
return val===undefined || val===null || val==='' || (Array.isArray(val) && val.length===0)
}
// ------------
// TEST
// ------------
var log = (name,val) => console.log(`${name} -> ${isEmpty(val)}`);
log('null', null);
log('undefined', undefined);
log('NaN', NaN);
log('""', "");
log('{}', {});
log('[]', []);
log('[1]', [1]);
log('[0]', [0]);
log('[[]]', [[]]);
log('true', true);
log('false', false);
log('"true"', "true");
log('"false"', "false");
log('Infinity', Infinity);
log('-Infinity', -Infinity);
log('1', 1);
log('0', 0);
log('-1', -1);
log('"1"', "1");
log('"0"', "0");
log('"-1"', "-1");
// "void 0" case
console.log('---\n"true" is:', true);
console.log('"void 0" is:', void 0);
log(void 0,void 0); // "void 0" is "undefined" - so we should get here TRUE
Here's mine - returns true if value is null, undefined, etc or blank (ie contains only blank spaces):
function stringIsEmpty(value) {
return value ? value.trim().length == 0 : true;
}
If you prefer plain javascript try this:
/**
* Checks if `value` is empty. Arrays, strings, or `arguments` objects with a
* length of `0` and objects with no own enumerable properties are considered
* "empty".
*
* #static
* #memberOf _
* #category Objects
* #param {Array|Object|string} value The value to inspect.
* #returns {boolean} Returns `true` if the `value` is empty, else `false`.
* #example
*
* _.isEmpty([1, 2, 3]);
* // => false
*
* _.isEmpty([]);
* // => true
*
* _.isEmpty({});
* // => true
*
* _.isEmpty('');
* // => true
*/
function isEmpty(value) {
if (!value) {
return true;
}
if (isArray(value) || isString(value)) {
return !value.length;
}
for (var key in value) {
if (hasOwnProperty.call(value, key)) {
return false;
}
}
return true;
}
Otherwise, if you are already using underscore or lodash, try:
_.isEmpty(value)
return val || 'Handle empty variable'
is a really nice and clean way to handle it in a lot of places, can also be used to assign variables
const res = val || 'default value'
If the variable hasn't been declared, you wont be able to test for undefined using a function because you will get an error.
if (foo) {}
function (bar) {}(foo)
Both will generate an error if foo has not been declared.
If you want to test if a variable has been declared you can use
typeof foo != "undefined"
if you want to test if foo has been declared and it has a value you can use
if (typeof foo != "undefined" && foo) {
//code here
}
You could use the nullish coalescing operator ?? to check for null and undefined values. See the MDN Docs
null ?? 'default string'; // returns "default string"
0 ?? 42; // returns 0
(null || undefined) ?? "foo"; // returns "foo"
To check Default Value
function typeOfVar (obj) {
return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}
function isVariableHaveDefaltVal(variable) {
if ( typeof(variable) === 'string' ) { // number, boolean, string, object
console.log(' Any data Between single/double Quotes is treated as String ');
return (variable.trim().length === 0) ? true : false;
}else if ( typeof(variable) === 'boolean' ) {
console.log('boolean value with default value \'false\'');
return (variable === false) ? true : false;
}else if ( typeof(variable) === 'undefined' ) {
console.log('EX: var a; variable is created, but has the default value of undefined.');
return true;
}else if ( typeof(variable) === 'number' ) {
console.log('number : '+variable);
return (variable === 0 ) ? true : false;
}else if ( typeof(variable) === 'object' ) {
// -----Object-----
if (typeOfVar(variable) === 'array' && variable.length === 0) {
console.log('\t Object Array with length = ' + [].length); // Object.keys(variable)
return true;
}else if (typeOfVar(variable) === 'string' && variable.length === 0 ) {
console.log('\t Object String with length = ' + variable.length);
return true;
}else if (typeOfVar(variable) === 'boolean' ) {
console.log('\t Object Boolean = ' + variable);
return (variable === false) ? true : false;
}else if (typeOfVar(variable) === 'number' ) {
console.log('\t Object Number = ' + variable);
return (variable === 0 ) ? true : false;
}else if (typeOfVar(variable) === 'regexp' && variable.source.trim().length === 0 ) {
console.log('\t Object Regular Expression : ');
return true;
}else if (variable === null) {
console.log('\t Object null value');
return true;
}
}
return false;
}
var str = "A Basket For Every Occasion";
str = str.replace(/\s/g, "-");
//The "g" flag in the regex will cause all spaces to get replaced.
check Result:
isVariableHaveDefaltVal(' '); // string
isVariableHaveDefaltVal(false); // boolean
var a;
isVariableHaveDefaltVal(a);
isVariableHaveDefaltVal(0); // number
isVariableHaveDefaltVal(parseInt('')); // NAN isNAN(' '); - true
isVariableHaveDefaltVal(null);
isVariableHaveDefaltVal([]);
isVariableHaveDefaltVal(/ /);
isVariableHaveDefaltVal(new Object(''));
isVariableHaveDefaltVal(new Object(false));
isVariableHaveDefaltVal(new Object(0));
typeOfVar( function() {} );
I used #Vix function() to check the object of which type.
using instansof «
var prototypes_or_Literals = function (obj) {
switch (typeof(obj)) {
// object prototypes
case 'object':
if (obj instanceof Array)
return '[object Array]';
else if (obj instanceof Date)
return '[object Date]';
else if (obj instanceof RegExp)
return '[object regexp]';
else if (obj instanceof String)
return '[object String]';
else if (obj instanceof Number)
return '[object Number]';
else
return 'object';
// object literals
default:
return typeof(obj);
}
};
output test «
prototypes_or_Literals( '' ) // "string"
prototypes_or_Literals( new String('') ) // "[object String]"
Object.prototype.toString.call("foo bar") //"[object String]"
function isEmpty(obj) {
if (typeof obj == 'number') return false;
else if (typeof obj == 'string') return obj.length == 0;
else if (Array.isArray(obj)) return obj.length == 0;
else if (typeof obj == 'object') return obj == null || Object.keys(obj).length == 0;
else if (typeof obj == 'boolean') return false;
else return !obj;
}
In ES6 with trim to handle whitespace strings:
const isEmpty = value => {
if (typeof value === 'number') return false
else if (typeof value === 'string') return value.trim().length === 0
else if (Array.isArray(value)) return value.length === 0
else if (typeof value === 'object') return value == null || Object.keys(value).length === 0
else if (typeof value === 'boolean') return false
else return !value
}
It may be usefull.
All values in array represent what you want to be (null, undefined or another things) and you search what you want in it.
var variablesWhatILookFor = [null, undefined, ''];
variablesWhatILookFor.indexOf(document.DocumentNumberLabel) > -1
If you are using TypeScript and don't want to account for "values those are false" then this is the solution for you:
First: import { isNullOrUndefined } from 'util';
Then: isNullOrUndefined(this.yourVariableName)
Please Note: As mentioned below this is now deprecated, use value === undefined || value === null instead. ref.
Try With Different Logic. You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.
function myFunction() {
var data; //The Values can be like as null, blank, undefined, zero you can test
if(!(!(data)))
{
alert("data "+data);
}
else
{
alert("data is "+data);
}
}
The optional chaining operator provides a way to simplify accessing values through connected objects when it's possible that a reference or function may be undefined or null.
let customer = {
name: "Carl",
details: {
age: 82,
location: "Paradise Falls" // detailed address is unknown
}
};
let customerCity = customer.details?.address?.city;
The nullish coalescing operator may be used after optional chaining in order to build a default value when none was found:
let customer = {
name: "Carl",
details: { age: 82 }
};
const customerCity = customer?.city ?? "Unknown city";
console.log(customerCity); // Unknown city
function isEmpty(val){
return !val;
}
but this solution is over-engineered, if you dont'want to modify the function later for busines-model needings, then is cleaner to use it directly in code:
if(!val)...
var myNewValue = myObject && myObject.child && myObject.child.myValue;
This will never throw an error. If myObject, child, or myValue is null then myNewValue will be null. No errors will be thrown
For everyone coming here for having similar question, the following works great and I have it in my library the last years:
(function(g3, $, window, document, undefined){
g3.utils = g3.utils || {};
/********************************Function type()********************************
* Returns a lowercase string representation of an object's constructor.
* #module {g3.utils}
* #function {g3.utils.type}
* #public
* #param {Type} 'obj' is any type native, host or custom.
* #return {String} Returns a lowercase string representing the object's
* constructor which is different from word 'object' if they are not custom.
* #reference http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
* http://stackoverflow.com/questions/3215046/differentiating-between-arrays-and-hashes-in-javascript
* http://javascript.info/tutorial/type-detection
*******************************************************************************/
g3.utils.type = function (obj){
if(obj === null)
return 'null';
else if(typeof obj === 'undefined')
return 'undefined';
return Object.prototype.toString.call(obj).match(/^\[object\s(.*)\]$/)[1].toLowerCase();
};
}(window.g3 = window.g3 || {}, jQuery, window, document));
If you want to avoid getting true if the value is any of the following, according to jAndy's answer:
null
undefined
NaN
empty string ("")
0
false
One possible solution that might avoid getting truthy values is the following:
function isUsable(valueToCheck) {
if (valueToCheck === 0 || // Avoid returning false if the value is 0.
valueToCheck === '' || // Avoid returning false if the value is an empty string.
valueToCheck === false || // Avoid returning false if the value is false.
valueToCheck) // Returns true if it isn't null, undefined, or NaN.
{
return true;
} else {
return false;
}
}
It would be used as follows:
if (isUsable(x)) {
// It is usable!
}
// Make sure to avoid placing the logical NOT operator before the parameter (isUsable(!x)) and instead, use it before the function, to check the returned value.
if (!isUsable(x)) {
// It is NOT usable!
}
In addition to those scenarios, you may want to return false if the object or array is empty:
Object: {} (Using ECMA 7+)
Array: [] (Using ECMA 5+)
You would go about it this way:
function isEmptyObject(valueToCheck) {
if(typeof valueToCheck === 'object' && !Object.keys(valueToCheck).length){
// Object is empty!
return true;
} else {
// Object is not empty!
return false;
}
}
function isEmptyArray(valueToCheck) {
if(Array.isArray(valueToCheck) && !valueToCheck.length) {
// Array is empty!
return true;
} else {
// Array is not empty!
return false;
}
}
If you wish to check for all whitespace strings (" "), you may do the following:
function isAllWhitespace(){
if (valueToCheck.match(/^ *$/) !== null) {
// Is all whitespaces!
return true;
} else {
// Is not all whitespaces!
return false;
}
}
Note: hasOwnProperty returns true for empty strings, 0, false, NaN, null, and undefined, if the variable was declared as any of them, so it might not be the best to use. The function may be modified to use it to show that it was declared, but is not usable.
Code on GitHub
const isEmpty = value => (
(!value && value !== 0 && value !== false)
|| (Array.isArray(value) && value.length === 0)
|| (isObject(value) && Object.keys(value).length === 0)
|| (typeof value.size === 'number' && value.size === 0)
// `WeekMap.length` is supposed to exist!?
|| (typeof value.length === 'number'
&& typeof value !== 'function' && value.length === 0)
);
// Source: https://levelup.gitconnected.com/javascript-check-if-a-variable-is-an-object-and-nothing-else-not-an-array-a-set-etc-a3987ea08fd7
const isObject = value =>
Object.prototype.toString.call(value) === '[object Object]';
Poor man's tests 😁
const test = () => {
const run = (label, values, expected) => {
const length = values.length;
console.group(`${label} (${length} tests)`);
values.map((v, i) => {
console.assert(isEmpty(v) === expected, `${i}: ${v}`);
});
console.groupEnd();
};
const empty = [
null, undefined, NaN, '', {}, [],
new Set(), new Set([]), new Map(), new Map([]),
];
const notEmpty = [
' ', 'a', 0, 1, -1, false, true, {a: 1}, [0],
new Set([0]), new Map([['a', 1]]),
new WeakMap().set({}, 1),
new Date(), /a/, new RegExp(), () => {},
];
const shouldBeEmpty = [
{undefined: undefined}, new Map([[]]),
];
run('EMPTY', empty, true);
run('NOT EMPTY', notEmpty, false);
run('SHOULD BE EMPTY', shouldBeEmpty, true);
};
Test results:
EMPTY (10 tests)
NOT EMPTY (16 tests)
SHOULD BE EMPTY (2 tests)
Assertion failed: 0: [object Object]
Assertion failed: 1: [object Map]
function notEmpty(value){
return (typeof value !== 'undefined' && value.trim().length);
}
it will also check white spaces (' ') along with following:
null ,undefined ,NaN ,empty ,string ("") ,0 ,false
I want to check return true if an array contains all integers or false if not. I am trying to use the every method MDN docs every.
So if given '1234' it will return true and if given '123a' it would return false.
function validatePIN (pin) {
pinArray = pin.split("");
if (pinArray.length === 4 || pinArray.length === 6) {
if (pinArray.every(Number.isInteger()) === true;) {
return true
}};
How does every pass the element to isInteger so it can test it?
Even if you fix syntax error and pass Number.isInteger as a function this won't work.
function wrongValidatePIN (pin) {
var pinArray = pin.split(""); // <-- array of strings
if (pinArray.length === 4 || pinArray.length === 6) {
if (pinArray.every(Number.isInteger)) { // <-- isInteger works with numbers
return true
}}
return false
}
console.log(wrongValidatePIN('1234'))
You need something like this
function validatePIN (pin) {
var pinArray = pin.split(""); // <-- array of strings
return (pinArray.length === 4 || pinArray.length === 6)
&& pinArray.every(char => !Number.isNaN(Number.parseInt(char, 10)))
}
console.log(validatePIN('1234'), validatePIN('123a'))
Or you could use regexp
function validatePin(pin) {
return /^(\d{4}|\d{6})$/.test(pin)
}
console.log(validatePin('1234'), validatePin('123456'),
validatePin('12345'), validatePin('123a'))
As the comments stated, the isInteger function can be passed as an argument by calling pinArray.every(Number.isInteger) instead of calling it a single time, (or by providing it inside a function .every(c=>Number.isInteger(c)) , but passing the function itself is more concise)
However, it's unlikely to provide the result you expect, because isInteger checks if the value is an actual integer, not if the value can be parsed to one.
That could be resolved with something like pinArray.map(parseFloat).every(Number.isInteger);
but then it would be easier to use !pinArray.some(isNaN)
That could make the function:
function validatePIN (pin) {
return (pin.length === 4 || pin.length === 6)
&& ![...pin].some(isNaN);
}
But as a final note, regular expressions are made for this type of check and could be preferable here
Your pin.split("") will never work when you pass number eg. 1234 as argument. Convert to string first then split pin.toString().split("").
Now inside .every() function we cast our string to number by doing +number.
return pinArray.every(number => Number.isInteger(+number));
.every() returns true or false.
Here is working example.
function validatePIN(pin) {
var pinArray = pin.toString().split("");
if (pinArray.length === 4 || pinArray.length === 6) {
// returns true or false
// +number casts string into number
return pinArray.every(number => Number.isInteger(+number));
}
// We assume that every PIN is not valid
return false;
};
console.log('test1', validatePIN(1234)); // true
console.log('test2', validatePIN('1234')); // true
console.log('test3', validatePIN('123a')); // false
console.log('test4', validatePIN('0001')); // true
Is there a universal JavaScript function that checks that a variable has a value and ensures that it's not undefined or null? I've got this code, but I'm not sure if it covers all cases:
function isEmpty(val){
return (val === undefined || val == null || val.length <= 0) ? true : false;
}
You can just check if the variable has a truthy value or not. That means
if (value) {
// do something..
}
will evaluate to true if value is not:
null
undefined
NaN
empty string ("")
0
false
The above list represents all possible falsy values in ECMA-/Javascript. Find it in the specification at the ToBoolean section.
Furthermore, if you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator. For instance
if (typeof foo !== 'undefined') {
// foo could get resolved and it's defined
}
If you can be sure that a variable is declared at least, you should directly check if it has a truthy value like shown above.
The verbose method to check if value is undefined or null is:
return value === undefined || value === null;
You can also use the == operator but this expects one to know all the rules:
return value == null; // also returns true if value is undefined
function isEmpty(value){
return (value == null || value.length === 0);
}
This will return true for
undefined // Because undefined == null
null
[]
""
and zero argument functions since a function's length is the number of declared parameters it takes.
To disallow the latter category, you might want to just check for blank strings
function isEmpty(value){
return (value == null || value === '');
}
Null or whitespace
function isEmpty(value){
return (value == null || value.trim().length === 0);
}
This is the safest check and I haven't seen it posted here exactly like that:
if (typeof value !== 'undefined' && value) {
//deal with value'
};
It will cover cases where value was never defined, and also any of these:
null
undefined (value of undefined is not the same as a parameter that was never defined)
0
"" (empty string)
false
NaN
Edited: Changed to strict equality (!==) because it's the norm by now ;)
You may find the following function useful:
function typeOf(obj) {
return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}
Or in ES7 (comment if further improvements)
function typeOf(obj) {
const { toString } = Object.prototype;
const stringified = obj::toString();
const type = stringified.split(' ')[1].slice(0, -1);
return type.toLowerCase();
}
Results:
typeOf(); //undefined
typeOf(null); //null
typeOf(NaN); //number
typeOf(5); //number
typeOf({}); //object
typeOf([]); //array
typeOf(''); //string
typeOf(function () {}); //function
typeOf(/a/) //regexp
typeOf(new Date()) //date
typeOf(new WeakMap()) //weakmap
typeOf(new Map()) //map
"Note that the bind operator (::) is not part of ES2016 (ES7) nor any later edition of the ECMAScript standard at all. It's currently a stage 0 (strawman) proposal for being introduced to the language." – Simon Kjellberg. the author wishes to add his support for this beautiful proposal to receive royal ascension.
A solution I like a lot:
Let's define that a blank variable is null, or undefined, or if it has length, it is zero, or if it is an object, it has no keys:
function isEmpty (value) {
return (
// null or undefined
(value == null) ||
// has length and it's zero
(value.hasOwnProperty('length') && value.length === 0) ||
// is an Object and has no keys
(value.constructor === Object && Object.keys(value).length === 0)
)
}
Returns:
true: undefined, null, "", [], {}
false: true, false, 1, 0, -1, "foo", [1, 2, 3], { foo: 1 }
This condition check
if (!!foo) {
//foo is defined
}
is all you need.
Take a look at the new ECMAScript Nullish coalescing operator
You can think of this feature - the ?? operator - as a way to “fall back” to a default value when dealing with null or undefined.
let x = foo ?? bar();
Again, the above code is equivalent to the following.
let x = (foo !== null && foo !== undefined) ? foo : bar();
The first answer with best rating is wrong. If value is undefined it will throw an exception in modern browsers. You have to use:
if (typeof(value) !== "undefined" && value)
or
if (typeof value !== "undefined" && value)
! check for empty strings (""), null, undefined, false and the number 0 and NaN. Say, if a string is empty var name = "" then console.log(!name) returns true.
function isEmpty(val){
return !val;
}
this function will return true if val is empty, null, undefined, false, the number 0 or NaN.
OR
According to your problem domain you can just use like !val or !!val.
You are a bit overdoing it. To check if a variable is not given a value, you would only need to check against undefined and null.
function isEmpty(value){
return (typeof value === "undefined" || value === null);
}
This is assuming 0, "", and objects(even empty object and array) are valid "values".
Vacuousness
I don't recommend trying to define or use a function which computes whether any value in the whole world is empty. What does it really mean to be "empty"? If I have let human = { name: 'bob', stomach: 'empty' }, should isEmpty(human) return true? If I have let reg = new RegExp('');, should isEmpty(reg) return true? What about isEmpty([ null, null, null, null ]) - this list only contains emptiness, so is the list itself empty? I want to put forward here some notes on "vacuousness" (an intentionally obscure word, to avoid pre-existing associations) in javascript - and I want to argue that "vacuousness" in javascript values should never be dealt with generically.
Truthiness/Falsiness
For deciding how to determine the "vacuousness" of values, we need to accomodate javascript's inbuilt, inherent sense of whether values are "truthy" or "falsy". Naturally, null and undefined are both "falsy". Less naturally, the number 0 (and no other number except NaN) is also "falsy". Least naturally: '' is falsy, but [] and {} (and new Set(), and new Map()) are truthy - although they all seem equally vacuous!
Null vs Undefined
There is also some discussion concerning null vs undefined - do we really need both in order to express vacuousness in our programs? I personally avoid ever having undefined appear in my code. I always use null to signify "vacuousness". Again, though, we need to accomodate javascript's inherent sense of how null and undefined differ:
Trying to access a non-existent property gives undefined
Omitting a parameter when calling a function results in that parameter receiving undefined:
let f = a => a;
console.log(f('hi'));
console.log(f());
Parameters with default values receive the default only when given undefined, not null:
let f = (v='hello') => v;
console.log(f(null));
console.log(f(undefined));
To me, null is an explicit signifier of vacuousness; "something that could have been filled in was intentionally left blank".
Really undefined is a necessary complication that allows some js features to exist, but in my opinion it should always be left behind the scenes; not interacted with directly. We can think of undefined as, for example, javascript's mechanic for implementing default function arguments. If you refrain from supplying an argument to a function it will receive a value of undefined instead. And a default value will be applied to a function argument if that argument was initially set to undefined. In this case undefined is the linchpin of default function arguments, but it stays in the background: we can achieve default argument functionality without ever referring to undefined:
This is a bad implementation of default arguments as it interacts directly with undefined:
let fnWithDefaults = arg => {
if (arg === undefined) arg = 'default';
...
};
This is a good implementation:
let fnWithDefaults = (arg='default') => { ... };
This is a bad way to accept the default argument:
fnWithDefaults(undefined);
Simply do this instead:
fnWithDefaults();
By the way: do you have a function with multiple arguments, and you want to provide some arguments while accepting defaults for others?
E.g.:
let fnWithDefaults = (a=1, b=2, c=3, d=4) => console.log(a, b, c, d);
If you want to provide values for a and d and accepts defaults for the others what to do? This seems wrong:
fnWithDefaults(10, undefined, undefined, 40);
The answer is: refactor fnWithDefaults to accept a single object:
let fnWithDefaults = ({ a=1, b=2, c=3, d=4 }={}) => console.log(a, b, c, d);
fnWithDefaults({ a: 10, d: 40 }); // Now this looks really nice! (And never talks about "undefined")
Non-generic Vacuousness
I believe that vacuousness should never be dealt with in a generic fashion. We should instead always have the rigour to get more information about our data before determining if it is vacuous - I mainly do this by checking what type of data I'm dealing with:
let isType = (value, Cls) => {
// Intentional use of loose comparison operator detects `null`
// and `undefined`, and nothing else!
return value != null && Object.getPrototypeOf(value).constructor === Cls;
};
Note that this function ignores inheritance - it expects value to be a direct instance of Cls, and not an instance of a subclass of Cls. I avoid instanceof for two main reasons:
([] instanceof Object) === true ("An Array is an Object")
('' instanceof String) === false ("A String is not a String")
Note that Object.getPrototypeOf is used to avoid an (obscure) edge-case such as let v = { constructor: String }; The isType function still returns correctly for isType(v, String) (false), and isType(v, Object) (true).
Overall, I recommend using this isType function along with these tips:
Minimize the amount of code processing values of unknown type. E.g., for let v = JSON.parse(someRawValue);, our v variable is now of unknown type. As early as possible, we should limit our possibilities. The best way to do this can be by requiring a particular type: e.g. if (!isType(v, Array)) throw new Error('Expected Array'); - this is a really quick and expressive way to remove the generic nature of v, and ensure it's always an Array. Sometimes, though, we need to allow v to be of multiple types. In those cases, we should create blocks of code where v is no longer generic, as early as possible:
if (isType(v, String)) {
/* v isn't generic in this block - It's a String! */
} else if (isType(v, Number)) {
/* v isn't generic in this block - It's a Number! */
} else if (isType(v, Array)) {
/* v isn't generic in this block - it's an Array! */
} else {
throw new Error('Expected String, Number, or Array');
}
Always use "whitelists" for validation. If you require a value to be, e.g., a String, Number, or Array, check for those 3 "white" possibilities, and throw an Error if none of the 3 are satisfied. We should be able to see that checking for "black" possibilities isn't very useful: Say we write if (v === null) throw new Error('Null value rejected'); - this is great for ensuring that null values don't make it through, but if a value does make it through, we still know hardly anything about it. A value v which passes this null-check is still VERY generic - it's anything but null! Blacklists hardly dispell generic-ness.
Unless a value is null, never consider "a vacuous value". Instead, consider "an X which is vacuous". Essentially, never consider doing anything like if (isEmpty(val)) { /* ... */ } - no matter how that isEmpty function is implemented (I don't want to know...), it isn't meaningful! And it's way too generic! Vacuousness should only be calculated with knowledge of val's type. Vacuousness-checks should look like this:
"A string, with no chars":
if (isType(val, String) && val.length === 0) ...
"An Object, with 0 props": if (isType(val, Object) && Object.entries(val).length === 0) ...
"A number, equal or less than zero": if (isType(val, Number) && val <= 0) ...
"An Array, with no items": if (isType(val, Array) && val.length === 0) ...
The only exception is when null is used to signify certain functionality. In this case it's meaningful to say: "A vacuous value": if (val === null) ...
The probably shortest answer is
val==null || val==''
if you change rigth side to val==='' then empty array will give false. Proof
function isEmpty(val){
return val==null || val==''
}
// ------------
// TEST
// ------------
var log = (name,val) => console.log(`${name} -> ${isEmpty(val)}`);
log('null', null);
log('undefined', undefined);
log('NaN', NaN);
log('""', "");
log('{}', {});
log('[]', []);
log('[1]', [1]);
log('[0]', [0]);
log('[[]]', [[]]);
log('true', true);
log('false', false);
log('"true"', "true");
log('"false"', "false");
log('Infinity', Infinity);
log('-Infinity', -Infinity);
log('1', 1);
log('0', 0);
log('-1', -1);
log('"1"', "1");
log('"0"', "0");
log('"-1"', "-1");
// "void 0" case
console.log('---\n"true" is:', true);
console.log('"void 0" is:', void 0);
log(void 0,void 0); // "void 0" is "undefined" - so we should get here TRUE
More details about == (source here)
BONUS: Reason why === is more clear than ==
To write clear and easy
understandable code, use explicite list of accepted values
val===undefined || val===null || val===''|| (Array.isArray(val) && val.length===0)
function isEmpty(val){
return val===undefined || val===null || val==='' || (Array.isArray(val) && val.length===0)
}
// ------------
// TEST
// ------------
var log = (name,val) => console.log(`${name} -> ${isEmpty(val)}`);
log('null', null);
log('undefined', undefined);
log('NaN', NaN);
log('""', "");
log('{}', {});
log('[]', []);
log('[1]', [1]);
log('[0]', [0]);
log('[[]]', [[]]);
log('true', true);
log('false', false);
log('"true"', "true");
log('"false"', "false");
log('Infinity', Infinity);
log('-Infinity', -Infinity);
log('1', 1);
log('0', 0);
log('-1', -1);
log('"1"', "1");
log('"0"', "0");
log('"-1"', "-1");
// "void 0" case
console.log('---\n"true" is:', true);
console.log('"void 0" is:', void 0);
log(void 0,void 0); // "void 0" is "undefined" - so we should get here TRUE
Here's mine - returns true if value is null, undefined, etc or blank (ie contains only blank spaces):
function stringIsEmpty(value) {
return value ? value.trim().length == 0 : true;
}
If you prefer plain javascript try this:
/**
* Checks if `value` is empty. Arrays, strings, or `arguments` objects with a
* length of `0` and objects with no own enumerable properties are considered
* "empty".
*
* #static
* #memberOf _
* #category Objects
* #param {Array|Object|string} value The value to inspect.
* #returns {boolean} Returns `true` if the `value` is empty, else `false`.
* #example
*
* _.isEmpty([1, 2, 3]);
* // => false
*
* _.isEmpty([]);
* // => true
*
* _.isEmpty({});
* // => true
*
* _.isEmpty('');
* // => true
*/
function isEmpty(value) {
if (!value) {
return true;
}
if (isArray(value) || isString(value)) {
return !value.length;
}
for (var key in value) {
if (hasOwnProperty.call(value, key)) {
return false;
}
}
return true;
}
Otherwise, if you are already using underscore or lodash, try:
_.isEmpty(value)
return val || 'Handle empty variable'
is a really nice and clean way to handle it in a lot of places, can also be used to assign variables
const res = val || 'default value'
If the variable hasn't been declared, you wont be able to test for undefined using a function because you will get an error.
if (foo) {}
function (bar) {}(foo)
Both will generate an error if foo has not been declared.
If you want to test if a variable has been declared you can use
typeof foo != "undefined"
if you want to test if foo has been declared and it has a value you can use
if (typeof foo != "undefined" && foo) {
//code here
}
You could use the nullish coalescing operator ?? to check for null and undefined values. See the MDN Docs
null ?? 'default string'; // returns "default string"
0 ?? 42; // returns 0
(null || undefined) ?? "foo"; // returns "foo"
To check Default Value
function typeOfVar (obj) {
return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}
function isVariableHaveDefaltVal(variable) {
if ( typeof(variable) === 'string' ) { // number, boolean, string, object
console.log(' Any data Between single/double Quotes is treated as String ');
return (variable.trim().length === 0) ? true : false;
}else if ( typeof(variable) === 'boolean' ) {
console.log('boolean value with default value \'false\'');
return (variable === false) ? true : false;
}else if ( typeof(variable) === 'undefined' ) {
console.log('EX: var a; variable is created, but has the default value of undefined.');
return true;
}else if ( typeof(variable) === 'number' ) {
console.log('number : '+variable);
return (variable === 0 ) ? true : false;
}else if ( typeof(variable) === 'object' ) {
// -----Object-----
if (typeOfVar(variable) === 'array' && variable.length === 0) {
console.log('\t Object Array with length = ' + [].length); // Object.keys(variable)
return true;
}else if (typeOfVar(variable) === 'string' && variable.length === 0 ) {
console.log('\t Object String with length = ' + variable.length);
return true;
}else if (typeOfVar(variable) === 'boolean' ) {
console.log('\t Object Boolean = ' + variable);
return (variable === false) ? true : false;
}else if (typeOfVar(variable) === 'number' ) {
console.log('\t Object Number = ' + variable);
return (variable === 0 ) ? true : false;
}else if (typeOfVar(variable) === 'regexp' && variable.source.trim().length === 0 ) {
console.log('\t Object Regular Expression : ');
return true;
}else if (variable === null) {
console.log('\t Object null value');
return true;
}
}
return false;
}
var str = "A Basket For Every Occasion";
str = str.replace(/\s/g, "-");
//The "g" flag in the regex will cause all spaces to get replaced.
check Result:
isVariableHaveDefaltVal(' '); // string
isVariableHaveDefaltVal(false); // boolean
var a;
isVariableHaveDefaltVal(a);
isVariableHaveDefaltVal(0); // number
isVariableHaveDefaltVal(parseInt('')); // NAN isNAN(' '); - true
isVariableHaveDefaltVal(null);
isVariableHaveDefaltVal([]);
isVariableHaveDefaltVal(/ /);
isVariableHaveDefaltVal(new Object(''));
isVariableHaveDefaltVal(new Object(false));
isVariableHaveDefaltVal(new Object(0));
typeOfVar( function() {} );
I used #Vix function() to check the object of which type.
using instansof «
var prototypes_or_Literals = function (obj) {
switch (typeof(obj)) {
// object prototypes
case 'object':
if (obj instanceof Array)
return '[object Array]';
else if (obj instanceof Date)
return '[object Date]';
else if (obj instanceof RegExp)
return '[object regexp]';
else if (obj instanceof String)
return '[object String]';
else if (obj instanceof Number)
return '[object Number]';
else
return 'object';
// object literals
default:
return typeof(obj);
}
};
output test «
prototypes_or_Literals( '' ) // "string"
prototypes_or_Literals( new String('') ) // "[object String]"
Object.prototype.toString.call("foo bar") //"[object String]"
function isEmpty(obj) {
if (typeof obj == 'number') return false;
else if (typeof obj == 'string') return obj.length == 0;
else if (Array.isArray(obj)) return obj.length == 0;
else if (typeof obj == 'object') return obj == null || Object.keys(obj).length == 0;
else if (typeof obj == 'boolean') return false;
else return !obj;
}
In ES6 with trim to handle whitespace strings:
const isEmpty = value => {
if (typeof value === 'number') return false
else if (typeof value === 'string') return value.trim().length === 0
else if (Array.isArray(value)) return value.length === 0
else if (typeof value === 'object') return value == null || Object.keys(value).length === 0
else if (typeof value === 'boolean') return false
else return !value
}
It may be usefull.
All values in array represent what you want to be (null, undefined or another things) and you search what you want in it.
var variablesWhatILookFor = [null, undefined, ''];
variablesWhatILookFor.indexOf(document.DocumentNumberLabel) > -1
If you are using TypeScript and don't want to account for "values those are false" then this is the solution for you:
First: import { isNullOrUndefined } from 'util';
Then: isNullOrUndefined(this.yourVariableName)
Please Note: As mentioned below this is now deprecated, use value === undefined || value === null instead. ref.
Try With Different Logic. You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.
function myFunction() {
var data; //The Values can be like as null, blank, undefined, zero you can test
if(!(!(data)))
{
alert("data "+data);
}
else
{
alert("data is "+data);
}
}
The optional chaining operator provides a way to simplify accessing values through connected objects when it's possible that a reference or function may be undefined or null.
let customer = {
name: "Carl",
details: {
age: 82,
location: "Paradise Falls" // detailed address is unknown
}
};
let customerCity = customer.details?.address?.city;
The nullish coalescing operator may be used after optional chaining in order to build a default value when none was found:
let customer = {
name: "Carl",
details: { age: 82 }
};
const customerCity = customer?.city ?? "Unknown city";
console.log(customerCity); // Unknown city
function isEmpty(val){
return !val;
}
but this solution is over-engineered, if you dont'want to modify the function later for busines-model needings, then is cleaner to use it directly in code:
if(!val)...
var myNewValue = myObject && myObject.child && myObject.child.myValue;
This will never throw an error. If myObject, child, or myValue is null then myNewValue will be null. No errors will be thrown
For everyone coming here for having similar question, the following works great and I have it in my library the last years:
(function(g3, $, window, document, undefined){
g3.utils = g3.utils || {};
/********************************Function type()********************************
* Returns a lowercase string representation of an object's constructor.
* #module {g3.utils}
* #function {g3.utils.type}
* #public
* #param {Type} 'obj' is any type native, host or custom.
* #return {String} Returns a lowercase string representing the object's
* constructor which is different from word 'object' if they are not custom.
* #reference http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
* http://stackoverflow.com/questions/3215046/differentiating-between-arrays-and-hashes-in-javascript
* http://javascript.info/tutorial/type-detection
*******************************************************************************/
g3.utils.type = function (obj){
if(obj === null)
return 'null';
else if(typeof obj === 'undefined')
return 'undefined';
return Object.prototype.toString.call(obj).match(/^\[object\s(.*)\]$/)[1].toLowerCase();
};
}(window.g3 = window.g3 || {}, jQuery, window, document));
If you want to avoid getting true if the value is any of the following, according to jAndy's answer:
null
undefined
NaN
empty string ("")
0
false
One possible solution that might avoid getting truthy values is the following:
function isUsable(valueToCheck) {
if (valueToCheck === 0 || // Avoid returning false if the value is 0.
valueToCheck === '' || // Avoid returning false if the value is an empty string.
valueToCheck === false || // Avoid returning false if the value is false.
valueToCheck) // Returns true if it isn't null, undefined, or NaN.
{
return true;
} else {
return false;
}
}
It would be used as follows:
if (isUsable(x)) {
// It is usable!
}
// Make sure to avoid placing the logical NOT operator before the parameter (isUsable(!x)) and instead, use it before the function, to check the returned value.
if (!isUsable(x)) {
// It is NOT usable!
}
In addition to those scenarios, you may want to return false if the object or array is empty:
Object: {} (Using ECMA 7+)
Array: [] (Using ECMA 5+)
You would go about it this way:
function isEmptyObject(valueToCheck) {
if(typeof valueToCheck === 'object' && !Object.keys(valueToCheck).length){
// Object is empty!
return true;
} else {
// Object is not empty!
return false;
}
}
function isEmptyArray(valueToCheck) {
if(Array.isArray(valueToCheck) && !valueToCheck.length) {
// Array is empty!
return true;
} else {
// Array is not empty!
return false;
}
}
If you wish to check for all whitespace strings (" "), you may do the following:
function isAllWhitespace(){
if (valueToCheck.match(/^ *$/) !== null) {
// Is all whitespaces!
return true;
} else {
// Is not all whitespaces!
return false;
}
}
Note: hasOwnProperty returns true for empty strings, 0, false, NaN, null, and undefined, if the variable was declared as any of them, so it might not be the best to use. The function may be modified to use it to show that it was declared, but is not usable.
Code on GitHub
const isEmpty = value => (
(!value && value !== 0 && value !== false)
|| (Array.isArray(value) && value.length === 0)
|| (isObject(value) && Object.keys(value).length === 0)
|| (typeof value.size === 'number' && value.size === 0)
// `WeekMap.length` is supposed to exist!?
|| (typeof value.length === 'number'
&& typeof value !== 'function' && value.length === 0)
);
// Source: https://levelup.gitconnected.com/javascript-check-if-a-variable-is-an-object-and-nothing-else-not-an-array-a-set-etc-a3987ea08fd7
const isObject = value =>
Object.prototype.toString.call(value) === '[object Object]';
Poor man's tests 😁
const test = () => {
const run = (label, values, expected) => {
const length = values.length;
console.group(`${label} (${length} tests)`);
values.map((v, i) => {
console.assert(isEmpty(v) === expected, `${i}: ${v}`);
});
console.groupEnd();
};
const empty = [
null, undefined, NaN, '', {}, [],
new Set(), new Set([]), new Map(), new Map([]),
];
const notEmpty = [
' ', 'a', 0, 1, -1, false, true, {a: 1}, [0],
new Set([0]), new Map([['a', 1]]),
new WeakMap().set({}, 1),
new Date(), /a/, new RegExp(), () => {},
];
const shouldBeEmpty = [
{undefined: undefined}, new Map([[]]),
];
run('EMPTY', empty, true);
run('NOT EMPTY', notEmpty, false);
run('SHOULD BE EMPTY', shouldBeEmpty, true);
};
Test results:
EMPTY (10 tests)
NOT EMPTY (16 tests)
SHOULD BE EMPTY (2 tests)
Assertion failed: 0: [object Object]
Assertion failed: 1: [object Map]
function notEmpty(value){
return (typeof value !== 'undefined' && value.trim().length);
}
it will also check white spaces (' ') along with following:
null ,undefined ,NaN ,empty ,string ("") ,0 ,false