bradxr
8/8/2018 - 3:32 PM

The Spread Operator

Syntax is three dots (...) Performs several tasks: combines arrays, copies arrays, grabs items from arrays, collects function arguments as an array.

Src - “Learning React by Alex Banks and Eve Porcello (O’Reilly). Copyright 2017 Alex Banks, Eve Porcello, 978-1-491-95462-1.”

// using the spread operator to combine arrays
var peaks = ["Tallac", "Ralston", "Rose"]
var canyons = ["Ward", "Blackwood"]
var tahoe = [...peaks, ...canyons]

console.log(tahoe.join(', '))   // Tallac, Ralston, Rose, Ward, Blackwood


// using the spread operator to copy and reverse an array without mutating the original
var peaks = ["Tallac", "Ralston", "Rose"]
var [last] = [...peaks].reverse()

console.log(last)   // Rose
console.log(peaks.join(', '))   // Tallac, Ralston, Rose


// using the spread operator to grab items from arrays
var lakes = ["Donner", "Marlette", "Fallen Leaf", "Cascade"]
var [first, ...rest] = lakes

console.log(rest.join(', '))    // Marlette, Fallen Leaf, Cascade


// using the spread operator to collect function arguments as an array
function directions(...args) {
  var [start, ...remaining] = args
  var [finish, ...stops] = remaining.reverse()
  
  console.log(`drive through ${args.length} towns`)
  console.log(`start in ${start}`)
  console.log(`the destination is ${finish}`)
  console.log(`stopping ${stops.length} times in between`)
}

directions(
  "Truckee",
  "Tahoe City",
  "Sunnyside",
  "Homewood",
  "Tahoma"
)


// the spread operator can also be used with objects
// the below example combines two objects
var morning = {
  breakfast: "oatmeal",
  lunch: "peanut butter and jelly"
}

var dinner = "mac and cheese"

var backpackingMeal = {
  ...morning,
  dinner
}

console.log(backpackingMeals)
// {breakfast: "oatmeal", lunch: "peanut butter and jelly", dinner: "mac and cheese"}