Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save techieshravan/76ed828110723dce88e7e769a60d75fb to your computer and use it in GitHub Desktop.
Save techieshravan/76ed828110723dce88e7e769a60d75fb to your computer and use it in GitHub Desktop.
Destructuring in ECMAScript 2015
let numbers = [1, 2, 3, 4, 5];
let [a, b, c, d, e] = numbers;
console.log(a, b, c, d, e); //1 2 3 4 5
let numbers = [1, 2, [3, 4, [5, 6]]];
let [a, , [b, , [, c]]] = numbers;
console.log(a, b, c); //1 3 6
let numbers = [1, 2, 3, 4, 5];
let [a, b] = numbers;
console.log(a, b); //1 2
let [x, y, , , z] = numbers;
console.log(x, y, z); //1 2 5
let [i, , j, , k] = numbers;
console.log(i, j, k); //1 3 5
let numbers = [1, 2, 3, 4, 5];
let a, b, c, d, e;
[a, b, c, d, e] = numbers;
console.log(a, b, c, d, e); //1 2 3 4 5
let numbers = [1, 2, 3, 4, 5];
let [a, b, ...others] = numbers;
console.log(a, b); //1 2
console.log(others); //[3,4,5]
let x = 10, y = 20;
[x, y] = [y, x];
console.log(x, y); //20 10
var person = { name: 'Shravan', age: 27 };
//Object destructuring manually
var name = person.name;
var age = person.age;
console.log(name, age);
var numbers = [1, 2, 3, 4, 5];
//Array destructuring manually
var one = numbers[0];
var two = numbers[1];
console.log(one, two);
let fullName = { firstName: 'Shravan', lastName: 'Kasagoni' };
let {firstName: fn, lastName: ln} = fullName;
console.log(fn, ln); //Shravan Kasagoni
console.log(firstName, lastName); //throws an error
var fullName = {
firstName: 'Shravan',
lastName: 'Kasagoni'
};
let {firstName, lastName} = fullName;
console.log(firstName); //Shravan
console.log(lastName); //Kasagoni
let person = { name: 'Shravan', age: 27, mobile: undefined };
let {name, email = 'no email provided', mobile = '0000000000' } = person;
console.log(name, email, mobile); //Shravan no email provided 0000000000
let person = {
name: 'Shravan',
age: 27,
address: {
city: 'Hyderabad',
state: 'TS',
zip: 500001
}
};
let {name, age, address: {city, state, zip}} = person;
console.log(name, age, city, state, zip);
let person = { name: 'Shravan', age: 27 };
let {name, age, email} = person;
console.log(name, age, email); //Shravan 27 undefined
var person = {
name: 'Shravan',
age: 27,
email: 'shravan@theshravan.net'
};
displayPersonDetails(person);
function displayPersonDetails({name, age, email}) {
console.log(name, age, email);
}
function getPersonDetails() {
return {
name: 'Shravan',
age: 27,
email: 'shravan@theshravan.net'
};
}
let {name, age} = getPersonDetails();
console.log(name, age); //Shravan 27
var firstName, lastName;
({ firstName, lastName } = { firstName: 'Shravan', lastName: 'Kasagoni' });
console.log(firstName, lastName); //Shravan Kasagoni
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment