Skip to content

Instantly share code, notes, and snippets.

@koyta
Created May 25, 2017 10:51
Show Gist options
  • Save koyta/73cfd2470ef6431cfcd35e625834b55c to your computer and use it in GitHub Desktop.
Save koyta/73cfd2470ef6431cfcd35e625834b55c to your computer and use it in GitHub Desktop.
Destructing

Destructuring

const [a, b] = [10, 20];
const [c, d, ...other] = [30, 40, 50, 60, 70];

let x = 1;
let y = 2;
[x, y] = [y, x];

const [, second] = ['first', 'second'];

const [e] = []; // undefined
const [one = 1, two = 2] = [10];

const bob = {
	firstName: 'Bob',
	lastName: 'Smith',
	age: 20,
	gender: 'male',
};

const {firstName, lastName} = bob;

{
	// Experimental
	const {firstName, lastName, ...other} = bob;
}

const {firstName: f, lastName: l} = bob;

const {prop} = {}; // undefined
const {age, degree = 'none'} = bob;


// Short object key: value

const bob2 = {
	firstName,
	lastName,
	age: 40,
};

const {person: {name}} = {
	person: {
		name: 'Bob',
	},
};

const {employee: [{name: name2}]} = {
	employee: [
		{
			id: 1,
			name: 'Bob',
		},
		{
			id: 2,
			name: 'Karl',
		},
	],
};

const arr = [1, 2, 3, 4, 5, 6];
const arr2 = [
	...arr.slice(0, 2),
	30,
	...arr.slice( 3 ),
];
const arr3 = [...arr];
arr3[2] = 30;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment