Optional Chaining in JavaScript
If the below code blocks do not show up properly due to a recent Tumblr change. View them directly at https://obscurejavascript.tumblr.com/
Just like with optional function calls, it is possible to use a simple syntax for optional chaining. Firstly, without a library or helper method, getting a deep property safely can involve a lot of checks:
function printShortUrls(menu = []) { for (const option of menu) { if (option) { if (option.location && option.location.shortUrl) { console.log(option.title, ':', option.location.shortUrl); } else { console.log(option.title, ': (none)'); } } else { console.log('(empty)'); } } } const menu = [ { title: 'Dashboard', location: { fullUrl: 'https://my-website.com/dashboard/user1', shortUrl: 'https://goo.gl/929okH' } }, null,// Used to mark a menu separator { title: 'Logout', // No location since it redirects to a login page } ]; printShortUrls(menu); // Dashboard : https://goo.gl/929okH // (empty) // Logout : (none)
By using optional chaining, this can be simplified a lot:
function printShortUrls2(menu = []) { for (const option of menu) { if (option) { const shortUrl = option?.location?.shortUrl || '(none)'; console.log(option.title, ':', shortUrl); } else { console.log('(empty)'); } } }
Optional chaining is now supported in all major browsers. Though only very recently, so make sure you are on the latest version if running the code above on one of them. It is already in Node.js 14, but that version will not be ready for production use (for most people) until about October this year.
Github Location https://github.com/Jacob-Friesen/obscurejs/blob/master/2020/optionalChaining.js

















