Skip to content

Instantly share code, notes, and snippets.

@gwendall
Last active August 29, 2015 14:16
Show Gist options
  • Save gwendall/d5832a77014399ffadab to your computer and use it in GitHub Desktop.
Save gwendall/d5832a77014399ffadab to your computer and use it in GitHub Desktop.
Safe javascript variables
/*
Returns a nested property / executes a nested function from a variable, or a default value, without having it throwing any error
*/
var safeVar = function(string, def) {
var properties = string.split(".");
var filtered = [];
try {
properties.forEach(function(property) {
filtered.push(property);
eval(filtered);
});
} catch(err) {
return def;
}
return eval(string);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment