Skip to content

Instantly share code, notes, and snippets.

@minmaxdata
Forked from iHani/Destructuring.js
Created August 6, 2018 20:11
Show Gist options
  • Save minmaxdata/7320063b995a6f8341fafe6c80782c0b to your computer and use it in GitHub Desktop.
Save minmaxdata/7320063b995a6f8341fafe6c80782c0b to your computer and use it in GitHub Desktop.
Destructuring in ES2015 basic examples
/*
* Object Destructuring
*/
const book = {
title: 'ReWork',
author: 'Some guy',
publisher: {
name: 'Penguin'
}
}
const { title, author } = book // object destructuring is based on key value
const { name: publishedBy = 'Self-published' } = book.publisher // rename the key value and give it a deefault value
console.log(`Read ${title} by ${author}`);
console.log(`Published by ${publishedBy}`);
// Read ReWork by Some guy
// Published by Penguin
/*
* Array Destructuring
*/
const address = ['123 main st.', 'Denver', 'CO', '80203']
const [ , city, , zip ] = address // Array destructuring is based on position
console.log(`City is ${city} and zip is ${zip}`);
// City is Denver and zip is 80203
/*
* Destructuring Passed Arguments
*/
const obj = {
name: 'Hani',
favoriteFood: 'Mango'
}
const myFunc = ({ name: firstName, favoriteFood, favoriteColor: color = 'No color provided' }) => {
return `Hello ${firstName} your favorite food is ${favoriteFood} and your favorite color is ${color}`
}
console.log(myFunc(obj));
// Hello Hani your favorite food is Mango and your favorite color is No color provided
/*
* importing
*/
const { createStore } = Redux
// is equivalent to
var createStore = Redux.createStore
// and equivalent to
import { createStore } from 'redux'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment