I know Coffeescript. Why should I use this?
Well, now you can do that without all the question marks:
var access = ;;
I don't know Coffeescript. Why should I use this?
obj.that.is.very.nested will throw an error if the property
var nestedThang = objthat && objthatis && objthatisvery && objthatisverynested;
nestedThang will simply be
that doesn't exist (instead of throwing an error). But, this gets quite messy (and annoying to type out).
The equivalent, using
var access = ;var nestedThang = ;
safe-access can even be used to safely access arrays and call functions:
var obscenelyNested = ;
var obscenelyNested = obj &&objleading &&objleadingto &&objleadingtoarray &&objleadingtoarray0 &&objleadingtoarray0andFunc &&typeof objleadingtoarray0andFunc === 'function' ?objleadingtoarray0 :undefined;
Calling functions with arguments
Sometimes, it's necessary to call functions with some arguments. Every argument after the accessor string (3rd argument and beyond) will be used as the arguments to each function call in the accessor string. Like this:
// equivalent of `obj.thing.add(1, 2);`;
Or maybe you have multiple function calls that receive arguments:
// equivalent of `thing.add(1, 2).toFixed(1).substr(2);`;
Notice that if you need to pass in multiple arguments (like in the
add function), you'll need to pass the arguments as an array. The caveat is if you need to pass in an array as an argument, you'll need to pass in a nested array.
An example, passing in an array as an argument:
;// returns [ 'boop', 'beep', 'meep' ] OR undefined if window._ doesn't exist
safe-access auto-curries, which means omitting the second argument will return a function that you can use to access the same object over and over again. This can be useful if you are accessing many different nested properties on an object.
var objDot = ;; // obj.nested.thing; // obj.other.nested.thing