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,
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
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.
! 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
.
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)
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(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 === '');
}