Last active
August 29, 2015 14:16
-
-
Save gwendall/d5832a77014399ffadab to your computer and use it in GitHub Desktop.
Safe javascript variables
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 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