Skip to content

Instantly share code, notes, and snippets.

@adarrra
Last active May 4, 2017 10:10
Show Gist options
  • Save adarrra/b01176aea46315ea677a3ac45c4d3134 to your computer and use it in GitHub Desktop.
Save adarrra/b01176aea46315ea677a3ac45c4d3134 to your computer and use it in GitHub Desktop.
Destructuring examples + spread
// ========== OBJECTS ==================
// the most used
const {x} = {x: 1}; // x === 1
getSuggestions (request) {
const { prefix, bufferPosition, editor } = request;
}
// with new names
// in fact {prop} is short for {prop: prop}
let options = {
title: "Menu",
width: 100,
height: 200
};
let {width: w, height: h, title} = options; // w === 100
function showMenu({title, width, height}) {
alert(`${title} ${width} ${height}`);
}
showMenu(options); // Menu 100 200
// rename in short
// Destructuring target: the pattern used for destructuring = Destructuring source: the data to be destructured
const {x: y} = {x: 1}; // y === 1
// defaults
const {a, b=2} = {a: 1}; // b === 2
// computed property
let key = 'z';
let {[key]: foo} = {z: 'bar'};
// nested https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Nested_object_and_array_destructuring
let nested = {
name: "Kate",
hobbies: ["music", "dance", "CS"],
pets: [{cat: "Bazil"}, {dog: "Buddy"}],
parents: {
mom: "Eliza",
dad: "Olaf"
}
}
let {name: user, hobbies: [,, game], pets: [,{dog:pet}], parents: {mom}} = nested;
// user === "Kate", game == "CS", pet == "Buddy", mom == "Eliza"
// "assigment without declaration" https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Assignment_without_declaration
// http://stackoverflow.com/questions/29620686/is-it-possible-to-destructure-onto-an-existing-object-javascript-es6#comment49800234_29621542
// Starting with { implies a block scope, not an object literal.
// () converts to an expression.
let a, b;
({a, b} = {a: 1, b: 2});
coords = { lat: 121212, lng: 545}
otherObj = {latitude: 87687, longitude: 1234},
({lat: otherObj.latitude, lng: otherObj.longitude} = coords)
// equal
otherObj.latitude = coords.lat;
otherObj.longitude = coords.lng;
//or just use Object.assign({}, obj):
Object.assign(otherObj, coords )
let otherObj = Object.assign( {}, {
latitude: coords.lat,
longitude: coords.lng,
})
// =========== ARRAYS ===================
let [a, b, ...rest] = [10, 20, 30, 40, 50]; // a === 10, rest === [30, 40, 50]
// swap
[a, b] = [b, a];
// ignoring
let [a, , b] = [1, 2, 3]; // b === 3
// nested
let [a, [b, [c, d]]] = [1, [2, [[[3, 4], 5], 6]]];
// =========== SOME MORE USE CASES ===================
// for of loop
const arr = ['a', 'b'];
for (const [index, element] of arr.entries()) {
console.log(index, element);
}
// Output:
// 0 a
// 1 b
// ============= REST AND SPREAD ===========
// The spread operator has exactly the same syntax as the rest operator – three dots.
// But they are different
// Rest collects the remaining items of an iterable into an Array and is used for rest parameters and destructuring.
// Spread operator: turns the items of an iterable into arguments of a function call or into elements of an Array.
//REST
let [a, b, ...rest] = [10, 20, 30, 40, 50]; // a === 10, rest === [30, 40, 50]
//SPREAD 'concat'
const theEnd = [3, 4];
const allInOne = [1, 2, ...theEnd];
// allInOne == [1, 2, 3, 4]
// or the same results:
const first = [1 , 2];
first.push(...theEnd);
// or
let abc = ['a', 'b', 'c'];
let def = ['d', 'e', 'f'];
let alpha = [ ...abc, ...def ];
// alpha == ['a', 'b', 'c', 'd', 'e', 'f'];
//SPREAD unpack array
const theDate = [2015, 1, 1];
const date = new Date(...theDate);
// date === new Date(2015, 1, 1);
// or
Math.max(-1, ...[-1, 5, 11], 3) // and in cotrast to rest you can use it anywhere in a sequence of parts