Last active
June 16, 2021 09:44
-
-
Save zeusdeux/859ee97f703587dc63430d83ef66f75a to your computer and use it in GitHub Desktop.
Ways I use destructuring in JS
This file contains hidden or 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
// basic destructuring | |
const { key1 } = { key1: 10 } // key1 = 10 | |
const [x, y, z] = [1, 2, 3] // x = 1, y = 2, z = 3 | |
const [head, ...tail] = [1, 2, 3] // head = 1, tail = [2, 3] | |
const { a: { b } } = { a: { b: 20 } } // b = 20 | |
// storing value in a variable with a different name | |
const { key1: varForKey1 } = { key1: 20 } // varForKey1 = 20 | |
const { 'quoted-key': x } = { 'quoted-key': 10 } // x = 10 | |
// dependent default values part I | |
const { x, y = x } = { x: 20 } // x = 20, y = 20 | |
const { x, y = x } = { x: { a: 20 } } // x and y point to same object { a: 20 } | |
const { x = 'test', y = x } = {} // x = 'test', y = 'test' | |
// dependent default values part II | |
function fn(x = 0, y = x, z = x) { | |
// fn() -> 0 0 0 | |
// fn(10) -> 10 10 10 | |
// fn(10, 20) -> 10 20 10 | |
// fn(undefined, 9001) -> 0 9001 0 | |
console.log(x, y, z) | |
} | |
// with some tasty currying | |
var fn = (x = 10) => (y = x) => console.log(x, y) | |
// enforce mandatory param | |
function mandatory() { | |
throw new TypeError('Failed to provide a mandatory param') | |
} | |
function fn(mandatoryParam = mandatory()) { | |
console.log(mandatoryParam) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment