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
// 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
// laboratory

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

const { s: species = "rat", l: location = "laboratory" } = brain
// mouse
// laboratory

Photo by Robert Wiedemann on Unsplash