Skip to content

Instantly share code, notes, and snippets.

@mikaelbr
mikaelbr / destructuring.js
Last active February 21, 2024 20:41
Complete collection of JavaScript destructuring. Runnable demos and slides about the same topic: http://git.mikaelb.net/presentations/bartjs/destructuring
// === Arrays
var [a, b] = [1, 2];
console.log(a, b);
//=> 1 2
// Use from functions, only select from pattern
var foo = () => [1, 2, 3];
@kieraneglin
kieraneglin / safe-access-object.js
Last active February 28, 2019 13:01
Safely Access Deeply Nested Objects In JavaScript
// Problem: how do you access a deeply nested object that you're not certain exists?
// if(object.user && object.user.post && object.user.post[0] && object.user.post[0].comment) {
// return object.user.post[0].comment
// }
// and that's horrifying. Here's something better
const idx = (props, object) => props.reduce((prefix, val) => (prefix && prefix[val]) ? prefix[val] : null, object)
// Usage:
nestedObj = {...}