CodeBlanks Logo Icon CodeBlanks

Renaming

JavaScript course · Advanced · Lesson 27/100

Learn to assign a property to a variable with a different name in destructuring.

Renaming

Sometimes you dislike a property name, or two variables with the same name clash. In destructuring you use a colon to assign a property to a different variable: const { title: bookTitle } = book.

Here the value of book.title goes into the bookTitle variable. No title variable is created; only bookTitle. The right-hand name becomes the variable.

Renaming with a default

You can combine renaming with a default value. Writing const { count: total = 0 } = data moves data.count into a total variable; if the property is missing, total becomes 0.

The order is: first the property (count), then a colon, then the variable name (total), then an equals sign and the default. All in one line.

Exercise Rename book properties

Create a book object with title and year properties. Use destructuring to rename title into bookTitle and year into publishYear. Then log each one separately with console.log.

Show example solution
const book = { title: "Dune", year: 1965 };
const { title: bookTitle, year: publishYear } = book;
console.log(bookTitle);
console.log(publishYear);

Test yourself

  1. In `const { id: userId } = user`, which variable is created?

    • `userId`
    • `id`
    • both `id` and `userId`
    • no new variable is created
    Show answer

    `userId` — Correct. The name after the colon becomes the variable.

  2. Complete the renaming pattern

    const user = { name: "Alex" };
    const { name: ____ } = user;
    console.log(userName);
    Show answer
    const user = { name: "Alex" };
    const { name: userName } = user;
    console.log(userName);
  3. Which moves `count` into `total` and defaults to `0` when missing?

    • `const { count = total = 0 } = data`
    • `const { total: count = 0 } = data`
    • `const { count: total = 0 } = data`
    • `const { count, total = 0 } = data`
    Show answer

    `const { count: total = 0 } = data` — Correct. First the property, then a colon, then the variable, then an equals sign and the default.

  4. Match the concepts

    colon
    Renames the property
    renaming
    Takes a property under a new name
    right-hand name
    Becomes the variable name

All lessons in Advanced