Home > Web Front-end > JS Tutorial > body text

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

Barbara Streisand
Release: 2024-10-18 12:46:03
Original
391 people have browsed it

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>
Copy after login

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>
Copy after login

can be rewritten correctly as:

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

After this, the variables will be assigned as follows:

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

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!