Let's say I have a JavaScript object like:
var obj = {};
obj.computers = {};
obj.computers.favorite = "Commodore 64";
obj.computers.popular = "Apple";
Now, I can easily check for null like:
if(obj != 'undefined' && obj != null) {
if(obj.computers != 'undefined' && obj.computers != null)) {
.....
As you can see, if I need to see if obj.computers.favorite
has been set, I have to really nest some conditional logic there. Some of our objects go 3, 4, 5 levels deep.
This is what I would like to be able to do:
var fav = obj.computers.favorite || 'Unknown';
But I realize I would need to wrap that in some method. Something like:
var fav = getValueOrDefault(obj.computers.favorite, 'Unknown');
Suggestions appreciated.
Thanks
EDIT
My checking for 'undefined' isn't actually what I use. It just came out of my head when asking the question. lol
But I was wondering, could I just wrap in a try/catch and throw default if exception?
function(obj, default) {
try {
if(obj != null) {
return obj;
} else {
return default;
}
} catch(ex) {
return default;
}
}
Also, thanks to Shusi for pointing the redundant vars.