ES6: ...Spread & Rest

Jd Fiscus

... on an iterable

  • Array
  • String
  • DOM
  • Args
  • Objects
  • Maps
  • Sets

When Used

... on an iterable

  • Copies
    • Not destructive
  • Adds Map

Functionality

... on Grocery List

Example

let pizza = {
    name: 'Via 313',
    ingredients: ['Dough', 'Cheese', 'Sauce', 'Pepperoni'],
},
list = ['Milk','Bread']


let before = list.concat(pizza.ingredients)
console.log('Ok:', before)

const now = [...list, ...pizza.ingredients]
console.log('Spread:', now)

// ["Milk", "Bread", "Dough", "Cheese", "Sauce", "Pepperoni"]

... on the DOM

Example

<div>ATX</div>
<div>CHI</div>
<div>DET</div>
<div>NY</div>
console.log(document.querySelectorAll('div'))

const offices = [...document.querySelectorAll('div')].map(result => {
    console.log(result.textContent)
    return `${result.textContent}`
})

// ['ATX', 'DET', 'CHI', 'NY']

... on Arugments

Example

const name = ['Jd', 'Fiscus']

function hi(first, last) {

    alert(`Hello ${first} ${last}!`)
}

hi(...name)

... on Rest Params

Example

function total (rate, ...amounts) {
    return amounts.map(amount => amount * rate)
}

console.log(total(5, 8, 10, 4.5))

// [40, 50, 22.5]

... on Rest

Example

const detroit = ['Jd','Steph','Kevin','Matt']


const [mgmt, ...team] = detroit

console.log(mgmt, team)

// Jd ["Steph", "Kevin", "Matt"]

... on Data

Example

const offices = [
    {id: 512, name: 'Austin'},
    {id: 8348, name: 'Boise'},
    {id: 312, name: 'Chicago'},
    {id: 313, name: 'Detroit'},
    {id: 53540, name: 'Gotham'},
    {id: 678, name: 'New York'},
];


// Remove fake office
const id = 53540;
const officeIndex = offices.findIndex(office => office.id === id);

const realOffices = [...offices.slice(0, officeIndex), ...offices.slice(officeIndex+1)]

console.log(realOffices)

/* 
{id: 512, name: "Austin"}
{id: 8348, name: "Boise"}
{id: 312, name: "Chicago"}
{id: 313, name: "Detroit"}
{id: 678, name: "New York"}
*/

... on Object.assign

Example

var objOne = {name: 'Jd'};
var objTwo = {type: 'Standard Nerd'};

var newObjOne = Object.assign({}, objOne, objTwo);

var newObjTwo = {...objOne, ...objTwo};

// {name: "Jd", type: "Standard Nerd"}

... on Redux

Example

return {
  ...state,
  other: 'foo'
}

Resources

es6-spread-rest

By Jd Fiscus

es6-spread-rest

Presentation on spread & rest for ES6

  • 279
Loading comments...

More from Jd Fiscus