Skip to content

Instantly share code, notes, and snippets.

@huttj
Created December 31, 2014 18:49
Show Gist options
  • Save huttj/d1b73abace451ed3ca05 to your computer and use it in GitHub Desktop.
Save huttj/d1b73abace451ed3ca05 to your computer and use it in GitHub Desktop.
Safe property access in JavaScript
// 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
@huttj
Copy link
Author

huttj commented Dec 31, 2014

Note that it doesn't work with the traditional falsey values (e.g., 0).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment