developerasun / myCodeBox-web

Open source code box for web developers.
Apache License 2.0
5 stars 0 forks source link

[RESEARCH] Javascript/ES6: destructuring #255

Open developerasun opened 2 years ago

developerasun commented 2 years ago

topic : understanding destructuring in JS ES6

read this

ES6 is full of treats. Its additions really improve the coding experience in JavaScript and once again shows that JavaScript is here to stay. One of the new features is the ability of destructuring arrays and objects. This is an easy and convenient way of extracting data from arrays and objects.

destructruing array

Ok, let’s break down what this syntax actually does. By wrapping a variable declaration with square brackets, we’re saying that we want to take the first element from names and assign it to the variable — in our case assigning the first element to the variable first.

// destrucruing single element from array
const names = ['Luke', 'Eva', 'Phil'];  
const [first] = names;  
console.log(first); // 'Luke' 

// destrucruing multiple elements from array
const [first, second] = names;  
console.log(first, second); // 'Luke' 'Eva' 

// if not defined, return undefined
const [first, second, third, fourth] = names;  
console.log(fourth); // undefined 

// skipping a cerntain element
var [first, , second] = names;  
console.log(first, second); // 'Luke' 'Phil'

destructruing object

const person = {  
  name: 'Luke',
  age: '24',
  facts: {
    hobby: 'Photo',
    work: 'Software Developer'
  }
}

// extract multiple elements
const {name, age} = person;  
console.log(name, age); // 'Luke' '24'  

// extract deeper
const {facts: {hobby}} = person;  
console.log(hobby); // 'Photo'

// set default when not-existing
const {hometown = 'Unknown'} = person;  
console.log(hometown); // 'Unknown'

reference