Created
December 31, 2014 18:49
-
-
Save huttj/d1b73abace451ed3ca05 to your computer and use it in GitHub Desktop.
Safe property access in JavaScript
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
// Takes the first value after the last true value | |
var reverseCoalesce1 = true && 555 && 123; | |
console.log(reverseCoalesce1); // 123 | |
// If a value is null, it stops there | |
var reverseCoalesce2 = true && null && 123; | |
console.log(reverseCoalesce2); // null | |
// This is great for object access | |
var obj = {a: {b: {c: 2}}}; | |
var reverseCoalesce3 = obj && obj.a && obj.a.b && obj.a.b.c; | |
console.log(reverseCoalesce3); // 2 | |
// Trying to access a property that doesn't exist stops the chain--no errors! | |
var reverseCoalesce4 = obj && obj.a && obj.a.d && obj.a.d.c; | |
console.log(reverseCoalesce4); // undefined |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note that it doesn't work with the traditional falsey values (e.g., 0).