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

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

Linda Hamilton
Linda HamiltonOriginal
2024-10-18 13:22:301092browse

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

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

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!

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