Skip to content

Instantly share code, notes, and snippets.

@Kishanjvaghela
Last active January 11, 2017 10:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kishanjvaghela/12c21fb5dce32e9ba2e045d74feea8a2 to your computer and use it in GitHub Desktop.
Save Kishanjvaghela/12c21fb5dce32e9ba2e045d74feea8a2 to your computer and use it in GitHub Desktop.
Let's Learn ES6 - Destructuring
//1
let numbers = [10,20,30,40];
let first = numbers[0]; //10
let second = numbers[1]; //20
let [first,second] = numbers;
console.log(first); //10
console.log(second); //20
let [first,second,,fourth] = numbers;
console.log(fourth); //40
let [first,second,...theRest] = numbers;
console.log(first); //10
console.log(second); //20
console.log(theRest); //[30, 40]
// Destructuring
let { <KEY> : <NEW_VAR> } = <OBJECT>
let { <KEY> } = <OBJECT>
<KEY> : key that we want to grab value from
<NEW_VAR> : new variable that we are tring to create to store value in
<OBJECT> : Object from which we are taking value.
//////////////////////////////////////////////////////////////
// 1
let person={
name:"Kishan",
age:30,
location:"Toronto"
};
console.log(person.age); //30
console.log(person["age"]); //30
console.log(person['age']); //30
let {age:personAge} = person;
console.log(personAge); //30
let {age} = person;
console.log(age); //30
let {age , location : currentLocation} = person;
console.log(age); //30
console.log(currentLocation); //Toronto
let key = "age";
let { [key] : keyAge}=person;
console.log(keyAge); //30
///////////////////////////////////////////////////////////////////
//2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment