Today I Learned: Renaming Variables and Setting Default Values While Destructuring JS Objects

Thursday July 2, 2020 at 11:00 pm CDT

You have an object brain and you would like to assign its values to new variables:

let brain = { 
  s: "mouse",
  g: "try to take over the world",
  f: "Pinky"
}

You could use destructuring to grab those values:

const { s, g, f } = brain
console.log(s)
// mouse

Unfortunately, s, g, and f are not descriptive variables. You can rename the new variables while destructuring brain like so:

const { s: species, g: goal, f: friend } = brain

One can also provide default values in the case that the value in the object equals undefined.

const { s = "rat", l = "laboratory" } = brain
console.log(l)
// laboratory

You can rename variables and provide default values all at once:

const { s: species = "rat", l: location = "laboratory" } = brain
console.log(species)
// mouse
console.log(location)
// laboratory

Photo by Robert Wiedemann on Unsplash