Skip to content

Instantly share code, notes, and snippets.

@AbdallaZaki
Last active July 26, 2018 18:36
Show Gist options
  • Save AbdallaZaki/db16d3e013d45b062cffd141a3faa03f to your computer and use it in GitHub Desktop.
Save AbdallaZaki/db16d3e013d45b062cffd141a3faa03f to your computer and use it in GitHub Desktop.
// destruct array elements in variables
let arr = [1,2,3,4,5]
let [a,b] = arr
console.log(`a is ${a} and b is ${b}`)
//destruct array elements with skipping
let [a1, ,c]=arr
console.log(`a is ${a1} and b is ${c}`)
//destruct array to variables and array
let [elm1,elm2,...rest]=arr
console.log(`elm1 is ${elm1}, elm2 is ${elm2} and rest ${rest}`)
//destruct object to variables and array of properties
let {a:prop,b:prop2,...restPropObject}={a:1,b:2,c:3}
console.log(`prop is ${prop}, prop2 is ${prop2} and rest.c ${restPropObject.c}`)
//destruct with default value
let [elm11=1,elm21=2,...rest1] = [1,undefined,6]
console.log(`elm1 is ${elm11}, elm2 is ${elm21} and rest ${rest1}`)
// swaping fueture in arries
let val1=1,val2=3;
[val2,val1]=[val1,val2]
console.log(`val1 is ${val1}, val2 is ${val2}`)
// destruct with objects
let {a:a11,b:b1}= {a:1,b:2}
console.log(` a is ${a11}, b is ${b1}`)
// list of objects destruction
let people =[
{ name :"abdalla",
friends:[{
fname:"ahmed",
age:23
},{
fname:"khaled",
age:25
} ]
},{ name :"ali",
friends:[{
fname:"mohammed",
age:32
},{
fname:"saeed",
age:25
} ]
}
]
for(let{name,friends} of people){
for(let{fname} of friends){
console.log(fname)
}
console.log(name)
}
// claculated key in object destruction
let key = "c"
let {[key]:a22}={a:1,b:2,c:3}
console.log(a22)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment