AI Workshop: learn to build apps with AI →
JavaScript Recipes: Destructuring Tips

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


Rename Fields When Destructuring

Sometimes an object contains some set of properties, but you want to destructure it changing the names.

For example, a property name might not suit your naming convention, or you already have a variable with that name.

You can rename one of the fields using this syntax:

const person = {
  firstName: 'Tom',
  lastName: 'Cruise'
}

const { firstName: name, lastName } = person

name //Tom
lastName //Cruise

Destructure to an Already Defined Variable

Sometimes you need to assign the result of a function call to a variable already defined. The function returns an object:

function test() {
  return {
    one: 1,
    two: 2
  }
}

You might think you can just use object destructuring:

const { one, two } = test()

But if you have two already defined in your code (because of scoping issues), you can’t redeclare it:

let two

//...

const { one, two } = test() //ERROR

Solution 1: Use a Temporary Variable

const result = test()

two = result.two
const { one } = result

Solution 2: Use Parentheses

Declare one as let and use this syntax with parentheses (adding ; before them to prevent issues when you don’t use semicolons):

let one, two

;({ one, two } = test())

Any line starting with ( must start with a semicolon if you don’t use semicolons in your code.

Lessons in this unit:

0: Introduction
1: Generate Random Numbers in a Range
2: Get Index in for...of Loop
3: Unlimited Function Parameters
4: Return Result from Async Function
5: Encode and Decode URLs
6: ▶︎ Destructuring Tips
7: Number Formatting
8: Regex Recipes
9: Dynamic function name in JS