Skip to content

Instantly share code, notes, and snippets.

@whal-e3
Created November 25, 2020 01:58
Show Gist options
  • Save whal-e3/ce2451bff0f81029a7629be6ee8f4551 to your computer and use it in GitHub Desktop.
Save whal-e3/ce2451bff0f81029a7629be6ee8f4551 to your computer and use it in GitHub Desktop.
JS Destructuring - Object destructuring*
// Destructuring Assignment
let a, b;
[a, b] = [100, 200];
// Basic + (rest)
[a, b, c, ...rest] = [100, 200, 300, 400, 500];
// # OBJECT # + (rest)
({ a, b, ...rest } = { a: 100, b: 200, c: 300, d: 400, e: 500 });
// Array
const people = ['John', 'Beth', 'Mike'];
const [person1, person2, person3] = people;
// Parse array returned from function
function getPeople() {
return ['John', 'Beth', 'Mike'];
}
let person1, person2, person3;
[person1, person2, person3] = getPeople();
console.log(person1);
// ----------------------------------------------------------------------------
// * Object Destructuring *
const person = {
name: 'John Doe',
age: 32,
city: 'Miami',
gender: 'Male',
sayHello: function () {
console.log('Hello');
}
};
// Old ES5
// const name = person.name,
// age = person.age,
// city = person.city;
// NEW ES6
const { name, age, city, sayHello } = person;
sayHello();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment