Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Check undefined for Javascript
/**
* Returns true if key is not a key in object or object[key] has
* value undefined. If key is a dot-delimited string of key names,
* object and its sub-objects are checked recursively.
*/
function isUndefinedKey(object, key) {
var keyChain = Array.isArray(key) ? key : key.split('.'),
objectHasKey = keyChain[0] in object,
keyHasValue = typeof object[keyChain[0]] !== 'undefined';
if (objectHasKey && keyHasValue) {
if (keyChain.length > 1) {
return isUndefinedKey(object[keyChain[0]], keyChain.slice(1));
}
return false;
}
else {
return true;
}
}
var undefined,
ponies = {
pretty: false,
scummy: true,
favorite: {
food: 'money'
},
goodFor: undefined
};
isUndefinedKey(ponies, 'pretty'); // false
isUndefinedKey(ponies, 'goodFor'); // true
isUndefinedKey(ponies, 'anyValueWhatsoever'); // true
isUndefinedKey(ponies, 'favorite.food'); // false
//To check for undefined-valued object keys
key in obj && typeof obj.key === 'undefined';
// - or -
obj.hasOwnProperty(key) && typeof obj.key === 'undefined';
function isUndefined(value) {
return typeof value === 'undefined';
}
var a, x = 4;
isUndefined(a); // true
isUndefined(x); // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment