Last active
August 29, 2015 14:10
-
-
Save khanhtran3005/110d46e34c3bfa4ae521 to your computer and use it in GitHub Desktop.
Check undefined for Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//To check for undefined-valued object keys | |
key in obj && typeof obj.key === 'undefined'; | |
// - or - | |
obj.hasOwnProperty(key) && typeof obj.key === 'undefined'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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