ES6: Destructuring, Object Literal Enhancement and the Spread operator

Destructuring

Scoping an object locally

From an object

    var {pref1, pref2} = user  // user is object w/ keys pref1, pref2

From a functions arguments

    var function_x = ({firstname}) => {
      full_name = `${firstname} of boston`
    }

From an array

var [first_town] = ['Boston', 'Salem', 'Ham']  // 1st_town= Boston
var [,,last_town] = ['Boston', 'Salem', 'Ham']  // lst_town= Ham

Object Literal Enhancement

I’m guessing that name is going to change…
The opposite of destructuring.
Puts objects and methods together.

Objects from variables

var shell='bread'
var filling='butter'
var sandwich = {shell, filling}  
// New object 'sandwich' with contents
// {shell: 'bread', filling: 'butter'}

Object methods from variables

// Method is 'toast'
var toast = function() { console.log('Toast it for {time}') }
var toastedSandwich = {shell, filling, time}
toastedSandwich.toast

Spread Operator “...

Array values

The actual values from an array (not the array itself)

var arr1 = ['Buick', 'Ford']
var arr2= ['Edsel', 'Dodge']
var arr3 = [...arr1, ...arr2]

Function argument values as an array

function direction(...args) {}

Object Values

The key-value attributes from an object, not the object itself, e.g.

obj1={a:1, b:2}
obj2={c:3, d:4}
obj3={...obj1, ...obj2}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s