Deep property access in JavaScript
Have you ever found yourself repeatedly writing code like this?:
if (myObj && myObj.myProperty && myObj.myProperty.foo) {
doStuff(myObj.myProperty.foo);
}
That’s obviously because you would get reference errors if the sub-properties of your object don’t exist. I came across this too many times so I’ve written a helper function to get around this. You could do the same as above with this syntax:
doStuff(sprop(myObj, ‘myProperty.foo’));
EDIT:
After some benchmarking it turns out that this approach is significantly slower than using the typical multiple-if-statements approach. Also an iterating proves slightly faster than recursion. string.split() also adds a lot of overhead. Please use with caution and avoid usage in heavily executed code.
I updated the gist with the new code.


