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,
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:
undefined
, null
, ""
, []
, {}
true
, false
, 1
, 0
, -1
, "foo"
, [1, 2, 3]
, { foo: 1 }
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;
}
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)...
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 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
}
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