Home >Web Front-end >JS Tutorial >How to Rename Variables During Object Destructuring in ES6/ES2015?

How to Rename Variables During Object Destructuring in ES6/ES2015?

Barbara Streisand
Barbara StreisandOriginal
2024-10-18 12:46:03497browse

How to Rename Variables During Object Destructuring in ES6/ES2015?

Object Destructuring with Variable Renaming in ES6/ES2015

In JavaScript, object destructuring allows you to conveniently extract properties from an object into variables. However, what if you want to rename these variables during destructuring?

Instead of the incorrect syntax b as c highlighted in the question, ES6/ES2015 provides a proper way to rename target variables. You can directly assign new variable names using the following syntax:

<code class="js">const {oldName: newName} = object;</code>

For example, the original code:

<code class="js">const b = 6;
const test = { a: 1, b: 2 };
const {a, b as c} = test; // Incorrect</code>

can be rewritten correctly as:

<code class="js">const {a, b: c} = test; // Rename b to c</code>

After this, the variables will be assigned as follows:

<code class="js">a === 1
b === 6 // Original value unchanged
c === 2</code>

The above is the detailed content of How to Rename Variables During Object Destructuring in ES6/ES2015?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:The beauty of MSWNext article:The beauty of MSW