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

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

Linda Hamilton
Release: 2024-10-18 13:22:30
Original
896 people have browsed it

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

Object Destructuring with Target Variable Renaming in ES6/ES2015

Object destructuring is a concise and convenient way to extract properties from objects. However, what if you want to rename the target variables during destructuring? In this article, we'll explore how to achieve this in ES6/ES2015.

Renaming the Target Variable

The as keyword introduced in ES6/ES2015 allows you to assign a new name to the destructured property. This effectively renames the target variable.

const test = { a: 1, b: 2 };
const {a, b: c} = test;

console.log(a); // 1
console.log(c); // 2
Copy after login

In this example, the b property is destructured and assigned to the c variable using the as keyword. Consequently, the target variable referencing the b property is now c.

MDN Example

The Mozilla Developer Network (MDN) provides another clear example of object destructuring with target variable renaming:

var o = { p: 42, q: true };

// Assign new variable names
var { p: foo, q: bar } = o;

console.log(foo); // 42
console.log(bar); // true
Copy after login

In this example, the properties p and q are assigned to new variable names foo and bar respectively, using the as keyword.

The above is the detailed content of How to Rename Target Variables During 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!