Skip to content

Instantly share code, notes, and snippets.

@crapthings
Forked from mikaelbr/destructuring.js
Created December 21, 2016 07:34
Show Gist options
  • Select an option

  • Save crapthings/1255e67854e31f6765dbd9fde6c1a97d to your computer and use it in GitHub Desktop.

Select an option

Save crapthings/1255e67854e31f6765dbd9fde6c1a97d to your computer and use it in GitHub Desktop.
Several demos and usages for ES6 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);
var foo = function () {
return [1, 2, 3];
};
var [a, b] = foo();
console.log(a, b);
var foo = () => {
return [1, 2, 3];
};
var [a, , b] = foo();
console.log(a, b);
var [a, ...b] = [1, 2, 3];
console.log(a, b);
var [, , , a, b] = [1, 2, 3];
console.log(a, b);
// Swap variables
var a = 1, b = 2;
[b, a] = [a, b];
console.log(a, b);
// Advance deep arrays
var [a, [b, [c, d]]] = [1, [2, [[[3, 4], 5], 6]]];
console.log("a:", a, "b:", b, "c:", c, "d:", d);
// === Objects
var {user: x} = {user: 5};
console.log(x);
var {user: x} = {user2: 5};
console.log(x);
var {prop: x, prop2: y} = {prop: 5, prop2: 10};
console.log(x, y);
// Short-hand
var { prop, prop2} = {prop: 5, prop2: 10};
console.log(prop, prop2);
// Equal to:
var { prop: prop, prop2: prop2} = {prop: 5, prop2: 10};
console.log(prop, prop2);
// Combine objects an arrays
var {prop: x, prop2: [, y]} = {prop: 5, prop2: [10, 100]};
console.log(x, y);
// Deep objects
var {
prop: x,
prop2: {
prop2: {
nested: [ , , b]
}
}
} = { prop: "Hello", prop2: { prop2: { nested: ["a", "b", "c"]}}};
console.log(x, b);
// All well and good, can we do more? Yes!
// Using as method parameters
var foo = function ({prop: x}) {
console.log(x);
};
foo({invalid: 1});
foo({prop: 1});
// Can also use with the advance example
var foo = function ({
prop: x,
prop2: {
prop2: {
nested: b
}
}
}) {
console.log(x, ...b);
};
foo({ prop: "Hello", prop2: { prop2: { nested: ["a", "b", "c"]}}});
// Combine with other ES6 features.
var ajax = ({ url = "localhost", port: p = 80}, ...data) => {
console.log("Url:", url, "Port:", p, "Rest:", data);
};
ajax({
url: "someHost"
}, "additional", "data", "hello");
// Like _.pluck
var users = [
{ user: "Name1" },
{ user: "Name2" },
{ user: "Name2" },
{ user: "Name3" }
];
var names = users.map( ({ user }) => user );
console.log(names);
// Advanced usage with Array Comprehension and default values
var users = [
{ user: "Name1" },
{ user: "Name2", age: 2 },
{ user: "Name2" },
{ user: "Name3", age: 4 }
];
[for ({ user, age = "DEFAULT AGE" } of users) console.log(user, age)];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment