• Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Remember language
  • Português (do Brasil)

Destructuring assignment

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Description

The object and array literal expressions provide an easy way to create ad hoc packages of data.

The destructuring assignment uses similar syntax but uses it on the left-hand side of the assignment instead. It defines which values to unpack from the sourced variable.

Similarly, you can destructure objects on the left-hand side of the assignment.

This capability is similar to features present in languages such as Perl and Python.

For features specific to array or object destructuring, refer to the individual examples below.

Binding and assignment

For both object and array destructuring, there are two kinds of destructuring patterns: binding pattern and assignment pattern , with slightly different syntaxes.

In binding patterns, the pattern starts with a declaration keyword ( var , let , or const ). Then, each individual property must either be bound to a variable or further destructured.

All variables share the same declaration, so if you want some variables to be re-assignable but others to be read-only, you may have to destructure twice — once with let , once with const .

In many other syntaxes where the language binds a variable for you, you can use a binding destructuring pattern. These include:

  • The looping variable of for...in for...of , and for await...of loops;
  • Function parameters;
  • The catch binding variable.

In assignment patterns, the pattern does not start with a keyword. Each destructured property is assigned to a target of assignment — which may either be declared beforehand with var or let , or is a property of another object — in general, anything that can appear on the left-hand side of an assignment expression.

Note: The parentheses ( ... ) around the assignment statement are required when using object literal destructuring assignment without a declaration.

{ a, b } = { a: 1, b: 2 } is not valid stand-alone syntax, as the { a, b } on the left-hand side is considered a block and not an object literal according to the rules of expression statements . However, ({ a, b } = { a: 1, b: 2 }) is valid, as is const { a, b } = { a: 1, b: 2 } .

If your coding style does not include trailing semicolons, the ( ... ) expression needs to be preceded by a semicolon, or it may be used to execute a function on the previous line.

Note that the equivalent binding pattern of the code above is not valid syntax:

You can only use assignment patterns as the left-hand side of the assignment operator. You cannot use them with compound assignment operators such as += or *= .

Default value

Each destructured property can have a default value . The default value is used when the property is not present, or has value undefined . It is not used if the property has value null .

The default value can be any expression. It will only be evaluated when necessary.

Rest property

You can end a destructuring pattern with a rest property ...rest . This pattern will store all remaining properties of the object or array into a new object or array.

The rest property must be the last in the pattern, and must not have a trailing comma.

Array destructuring

Basic variable assignment, destructuring with more elements than the source.

In an array destructuring from an array of length N specified on the right-hand side of the assignment, if the number of variables specified on the left-hand side of the assignment is greater than N , only the first N variables are assigned values. The values of the remaining variables will be undefined.

Swapping variables

Two variables values can be swapped in one destructuring expression.

Without destructuring assignment, swapping two values requires a temporary variable (or, in some low-level languages, the XOR-swap trick ).

Parsing an array returned from a function

It's always been possible to return an array from a function. Destructuring can make working with an array return value more concise.

In this example, f() returns the values [1, 2] as its output, which can be parsed in a single line with destructuring.

Ignoring some returned values

You can ignore return values that you're not interested in:

You can also ignore all returned values:

Using a binding pattern as the rest property

The rest property of array destructuring assignment can be another array or object binding pattern. The inner destructuring destructures from the array created after collecting the rest elements, so you cannot access any properties present on the original iterable in this way.

These binding patterns can even be nested, as long as each rest property is the last in the list.

On the other hand, object destructuring can only have an identifier as the rest property.

Unpacking values from a regular expression match

When the regular expression exec() method finds a match, it returns an array containing first the entire matched portion of the string and then the portions of the string that matched each parenthesized group in the regular expression. Destructuring assignment allows you to unpack the parts out of this array easily, ignoring the full match if it is not needed.

Using array destructuring on any iterable

Array destructuring calls the iterable protocol of the right-hand side. Therefore, any iterable, not necessarily arrays, can be destructured.

Non-iterables cannot be destructured as arrays.

Iterables are only iterated until all bindings are assigned.

The rest binding is eagerly evaluated and creates a new array, instead of using the old iterable.

Object destructuring

Basic assignment, assigning to new variable names.

A property can be unpacked from an object and assigned to a variable with a different name than the object property.

Here, for example, const { p: foo } = o takes from the object o the property named p and assigns it to a local variable named foo .

Assigning to new variable names and providing default values

A property can be both

  • Unpacked from an object and assigned to a variable with a different name.
  • Assigned a default value in case the unpacked value is undefined .

Unpacking properties from objects passed as a function parameter

Objects passed into function parameters can also be unpacked into variables, which may then be accessed within the function body. As for object assignment, the destructuring syntax allows for the new variable to have the same name or a different name than the original property, and to assign default values for the case when the original object does not define the property.

Consider this object, which contains information about a user.

Here we show how to unpack a property of the passed object into a variable with the same name. The parameter value { id } indicates that the id property of the object passed to the function should be unpacked into a variable with the same name, which can then be used within the function.

You can define the name of the unpacked variable. Here we unpack the property named displayName , and rename it to dname for use within the function body.

Nested objects can also be unpacked. The example below shows the property fullname.firstName being unpacked into a variable called name .

Setting a function parameter's default value

Default values can be specified using = , and will be used as variable values if a specified property does not exist in the passed object.

Below we show a function where the default size is 'big' , default co-ordinates are x: 0, y: 0 and default radius is 25.

In the function signature for drawChart above, the destructured left-hand side has a default value of an empty object = {} .

You could have also written the function without that default. However, if you leave out that default value, the function will look for at least one argument to be supplied when invoked, whereas in its current form, you can call drawChart() without supplying any parameters. Otherwise, you need to at least supply an empty object literal.

For more information, see Default parameters > Destructured parameter with default value assignment .

Nested object and array destructuring

For of iteration and destructuring, computed object property names and destructuring.

Computed property names, like on object literals , can be used with destructuring.

Invalid JavaScript identifier as a property name

Destructuring can be used with property names that are not valid JavaScript identifiers by providing an alternative identifier that is valid.

Destructuring primitive values

Object destructuring is almost equivalent to property accessing . This means if you try to destruct a primitive value, the value will get wrapped into the corresponding wrapper object and the property is accessed on the wrapper object.

Same as accessing properties, destructuring null or undefined throws a TypeError .

This happens even when the pattern is empty.

Combined array and object destructuring

Array and object destructuring can be combined. Say you want the third element in the array props below, and then you want the name property in the object, you can do the following:

The prototype chain is looked up when the object is deconstructed

When deconstructing an object, if a property is not accessed in itself, it will continue to look up along the prototype chain.

Specifications

Browser compatibility.

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

  • Assignment operators
  • ES6 in Depth: Destructuring on hacks.mozilla.org (2015)

Rename Variables When Using Object Destructuring in JavaScript

When destructuring an object, you can rename the variables like so:

This is perfect for cases where you want to rename variables from a REST API whose naming conventions don't line up with yours. For example, switching variables from snake_case to camelCase or vice versa.

More Fundamentals Tutorials

  • The `setTimeout()` Function in JavaScript
  • JavaScript Array flatMap()
  • How to Get Distinct Values in a JavaScript Array
  • Check if a Date is Valid in JavaScript
  • Encode base64 in JavaScript
  • Check if URL Contains a String
  • JavaScript Add Month to Date

HatchJS Logo

HatchJS.com

Cracking the Shell of Mystery

JavaScript Object Destructuring Rename: How to Rename Object Properties in JavaScript

Avatar

JavaScript Object Destructuring Rename: A Powerful Tool for Refactoring

JavaScript object destructuring is a powerful tool that can be used to improve the readability and maintainability of your code. It allows you to extract the properties of an object into separate variables, which can make your code more concise and easier to understand.

In this article, we’ll take a look at object destructuring rename, a technique that can be used to rename the properties of an object when you destructure it. We’ll show you how to use object destructuring rename to improve the readability of your code and make it easier to maintain.

We’ll also discuss some of the limitations of object destructuring rename and how to work around them. By the end of this article, you’ll have a solid understanding of object destructuring rename and how to use it to improve your JavaScript code.

What is Object Destructuring?

Object destructuring is a JavaScript feature that allows you to extract the properties of an object into separate variables. This can be done when you declare a variable or when you assign a value to a variable.

For example, the following code declares a variable called `user` and extracts the `name` and `age` properties of the `user` object into separate variables:

js const user = { name: “John Doe”, age: 25 };

const { name, age } = user;

Now, the `name` and `age` variables contain the values of the corresponding properties of the `user` object. We can use these variables to access the properties of the `user` object without having to refer to the object itself.

For example, the following code prints the `name` and `age` of the `user` object:

js console.log(name); // John Doe console.log(age); // 25

Object Destructuring Rename

Object destructuring rename is a technique that can be used to rename the properties of an object when you destructure it. This can be useful when you want to give the properties of an object more descriptive names.

For example, the following code declares a variable called `user` and extracts the `name` and `age` properties of the `user` object into separate variables. The `name` property is renamed to `firstName` and the `age` property is renamed to `lastName`:

const { firstName: name, lastName: age } = user;

Now, the `name` variable contains the value of the `firstName` property of the `user` object, and the `age` variable contains the value of the `lastName` property of the `user` object.

Limitations of Object Destructuring Rename

Object destructuring rename has some limitations. For example, you cannot rename a property that is a nested object or array. You can only rename properties that are simple values, such as strings, numbers, or booleans.

Additionally, you cannot rename a property that is a function. If you try to rename a function property, you will get an error.

Working Around Limitations

There are a few ways to work around the limitations of object destructuring rename. One way is to use a utility function to rename the properties of an object. For example, the following function can be used to rename the properties of an object:

js function renameProperties(obj, renames) { const newObj = {};

for (const key in obj) { if (renames.hasOwnProperty(key)) { newObj[renames[key]] = obj[key]; } else { newObj[key] = obj[key]; } }

return newObj; }

This function takes two arguments: the object to be renamed and an object that maps the old property names to the new property names. The function returns a new object with the renamed properties.

For example, the following code uses the `renameProperties` function to rename the properties of the `user` object:

const renamedUser = renameProperties(user, { name: “firstName”, age: “lastName” });

console.log(renamedUser); // { firstName: “John Doe”, lastName: 25 }

Another way to work around the limitations of object destructuring rename is to use a template literal. A template

Object destructuring is a JavaScript feature that allows you to extract the properties of an object into separate variables. This can be useful for making your code more readable and concise.

Object destructuring rename is a variation of object destructuring that allows you to rename the properties of an object when you destructure it. This can be even more useful for making your code more readable and concise.

In this guide, we will show you how to use object destructuring rename in JavaScript. We will also provide some examples of how you can use object destructuring rename to improve the readability and conciseness of your code.

What is object destructuring rename?

Object destructuring rename is a JavaScript feature that allows you to rename the properties of an object when you destructure it. This can be useful for making your code more readable and concise.

To use object destructuring rename, you simply need to use the `as` keyword when you destructure an object. For example, the following code destructures the `user` object and renames the `name` property to `username`:

javascript const { name: username } = user;

This code is equivalent to the following code:

javascript const username = user.name;

However, the code using object destructuring rename is more readable and concise.

How to use object destructuring rename?

You can also rename multiple properties of an object at the same time. For example, the following code destructures the `user` object and renames the `name` and `email` properties to `username` and `useremail`, respectively:

javascript const { name: username, email: useremail } = user;

You can also use object destructuring rename to rename nested properties of an object. For example, the following code destructures the `user` object and renames the `address` property to `useraddress` and the `address.street` property to `userstreet`:

javascript const { address: { street: userstreet } } = user;

Examples of object destructuring rename

Here are some examples of how you can use object destructuring rename to improve the readability and conciseness of your code:

  • Renaming a single property

javascript const user = { name: “John Doe”, email: “ [email protected] ”, };

const { name: username } = user;

console.log(username); // John Doe

  • Renaming multiple properties

javascript const user = { name: “John Doe”, email: “ [email protected] ”, address: { street: “123 Main Street”, city: “Anytown”, state: “CA”, zipcode: “12345”, }, };

const { name: username, email: useremail, address: { street: userstreet } } = user;

console.log(username); // John Doe console.log(useremail); // [email protected] console.log(userstreet); // 123 Main Street

  • Renaming nested properties

const { address: { street: userstreet } } = user;

console.log(userstreet); // 123 Main Street

Object destructuring rename is a powerful JavaScript feature that can be used to make your code more readable and concise. By renaming the properties of an object, you can make it easier to understand what your code is doing.

In this guide, we have shown you how to use object destructuring rename. We have also provided some examples of how you can use object destructuring rename to improve the readability and conciseness of your code.

We hope that you have found this guide helpful. If you have any questions, please feel free

3. Benefits of using object destructuring rename

There are a few benefits to using object destructuring rename. First, it can make your code more readable and concise. When you destructure an object, you can omit the property names, which can make your code more compact and easier to read. For example, the following code destructures the `user` object and assigns the `name` property to the variable `username`:

javascript const { name } = user;

This code is much shorter and easier to read than the following code, which accesses the `name` property using the dot notation:

Second, object destructuring rename can help you to avoid errors by making it clear which property you are accessing. When you use the dot notation to access a property, it is possible to accidentally mistype the property name, which can result in an error. With object destructuring rename, you can avoid this problem by explicitly specifying the property name. For example, the following code destructures the `user` object and assigns the `name` property to the variable `username`:

This code makes it clear that the `username` variable is assigned the value of the `name` property. If you accidentally mistype the property name, the compiler will flag an error.

Third, object destructuring rename can make your code more maintainable by making it easier to change the names of your properties. If you need to change the name of a property in your object, you only need to change the name in the object destructuring statement. You do not need to update any of the code that uses the property. For example, the following code destructures the `user` object and assigns the `name` property to the variable `username`:

If you later decide to change the name of the `name` property to `displayName`, you can simply update the object destructuring statement:

javascript const { displayName: username } = user;

This change will be automatically reflected in any code that uses the `username` variable.

4. Examples of object destructuring rename

Here are a few examples of object destructuring rename:

javascript // Destructure the `user` object and rename the `name` property to `username`. const { name: username } = user;

// Destructure the `user` object and rename the `name` and `email` properties to `username` and `emailAddress`. const { name: username, email: emailAddress } = user;

// Destructure the `user` object and rename all of the properties to new names. const { firstName: newFirstName, lastName: newLastName, email: newEmailAddress } = user;

In each of these examples, the object destructuring statement renames the properties of the `user` object. This makes the code more readable and concise, and it helps to avoid errors.

5. How to use object destructuring rename

To use object destructuring rename, you need to use the following syntax:

javascript const { [newPropertyName]: propertyName } = object;

In this syntax, the `newPropertyName` is the new name that you want to give to the property, and the `propertyName` is the name of the property in the object. For example, the following code destructures the `user` object and renames the `name` property to `username`:

This code is equivalent to the following code, which accesses the `name` property using the dot notation:

However, the object destructuring statement is more concise and readable.

Object destructuring rename is a powerful tool that can make your code more readable, concise, and maintainable. By using object destructuring rename, you can avoid errors, make your code easier to understand, and make it easier to change the names of your properties.

Q: What is object destructuring in JavaScript?

A: Object destructuring is a JavaScript feature that allows you to extract the properties of an object into variables. This can be useful for reducing the amount of code you need to write, and for making your code more readable.

Q: How do I use object destructuring in JavaScript?

A: To use object destructuring, you can use the following syntax:

const { property1, property2 } = object;

This will create two variables, `property1` and `property2`, which will be assigned the values of the `property1` and `property2` properties of the `object` object.

Q: Can I rename the properties that I destructure?

A: Yes, you can rename the properties that you destructure by using the following syntax:

const { property1: newProperty1, property2: newProperty2 } = object;

This will create two variables, `newProperty1` and `newProperty2`, which will be assigned the values of the `property1` and `property2` properties of the `object` object.

Q: What are the benefits of using object destructuring?

A: There are a few benefits to using object destructuring in JavaScript. These include:

  • Reduced code size: Object destructuring can help you to reduce the amount of code that you need to write. This can be especially helpful when you are working with large objects.
  • Improved readability: Object destructuring can make your code more readable, as it can help to make it easier to understand what each variable is used for.
  • More concise code: Object destructuring can help you to write more concise code, as it can reduce the need for nested loops and conditional statements.

Q: Are there any limitations to object destructuring?

A: There are a few limitations to object destructuring. These include:

  • Not all properties can be destructured: You cannot destructure properties that are not enumerable.
  • Destructuring cannot be used with methods: You cannot destructure methods of an object.
  • Destructuring cannot be used with constructors: You cannot destructure constructors of an object.

Q: What are some common mistakes that people make when using object destructuring?

A: There are a few common mistakes that people make when using object destructuring. These include:

  • Not using the correct syntax: The syntax for object destructuring can be a bit tricky, so it is important to make sure that you are using it correctly.
  • Trying to destructure properties that are not enumerable: You cannot destructure properties that are not enumerable, so you will need to check to make sure that the properties that you want to destructure are actually enumerable.
  • Destructuring methods or constructors: You cannot destructure methods or constructors, so you will need to use a different approach if you want to access these properties.

Q: Where can I learn more about object destructuring in JavaScript?

A: There are a few resources that you can use to learn more about object destructuring in JavaScript. These include:

  • [The official JavaScript documentation on object destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)
  • [MDN Web Docs on object destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)

We hope that you have found this article helpful. Please feel free to leave any comments or questions below.

Author Profile

Marcus Greenwood

Latest entries

  • December 26, 2023 Error Fixing User: Anonymous is not authorized to perform: execute-api:invoke on resource: How to fix this error
  • December 26, 2023 How To Guides Valid Intents Must Be Provided for the Client: Why It’s Important and How to Do It
  • December 26, 2023 Error Fixing How to Fix the The Root Filesystem Requires a Manual fsck Error
  • December 26, 2023 Troubleshooting How to Fix the `sed unterminated s` Command

Similar Posts

Scala to java converter: a step-by-step guide.

Scala to Java Converter: A Quick and Easy Way to Port Your Code Scala and Java are two of the most popular programming languages for developing complex applications. While Scala offers a number of benefits over Java, such as its functional programming capabilities and its concise syntax, it can sometimes be difficult to port Scala…

Module java.base does not open java.util to unnamed module: What does this mean and how to fix it?

Java.base Does Not Open java.util to Unnamed Modules Java.base is the default module that all Java applications depend on. It provides a number of core classes and interfaces, including those for networking, I/O, and threading. However, java.base does not open java.util to unnamed modules. This means that if you try to import java.util from an…

Java SQL SQLException: Invalid Column Name

Have you ever encountered a Java SQL Exception with the message “Invalid column name”? If so, you’re not alone. This is a common error that can occur for a variety of reasons. In this article, we’ll take a look at what causes this error and how to fix it. We’ll start by discussing what a…

Java SQL SQLException: No Suitable Driver

Java SQL SQLException No Suitable Driver When you’re working with Java and SQL, you may encounter the dreaded SQLException “No suitable driver found”. This error can be caused by a number of things, but it usually means that your Java application can’t find the JDBC driver that it needs to connect to your database. In…

How to Run JavaScript in Visual Studio Code – A Step-by-Step Guide

How to Run JavaScript in Visual Studio Code Visual Studio Code is a popular code editor that can be used for a variety of programming languages, including JavaScript. Running JavaScript in Visual Studio Code is a simple process, and this guide will walk you through the steps. Prerequisites Before you can run JavaScript in Visual…

How to Fix Suppressed: java.lang.Exception: block terminated with an error

Have you ever encountered a Java exception that seemed to come out of nowhere? You might have been working on your code for hours, and then suddenly, you get a `java.lang.Exception: block terminated with an error`. This can be incredibly frustrating, especially when you don’t know what caused the exception. In this article, we’ll take…

Atomized Objects

Follow me on:

How to rename a destructured variable in JavaScript

How to rename a destructured variable in JavaScript

Destructuring in JavaScript is a useful tool that saves time and makes it easy to pick fields from objects, it becomes even more powerful when renaming destructured variables.

Will Mayger

In this post we will be covering how to rename a destructured variable in JavaScript with as little technical jargon as possible so you will have everything you need right here without having to look any further!

Often in JavaScript when you destructure a variable, argument, or prop you will need or want to rename it.

It might seem confusing at first, and a little tricky to remember which way round it works but all in all it is pretty easy to rename a destructured variable in JavaScript (destructuring assignment).

Destructuring assignment or renaming a destructured variable in JavaScript is very similar to creating a field in an object, except instead of saving a variable to a field you are naming one of the fields from the object you are destructuring.

When renaming a destructured variable in JavaScript the left hand side will be the original field in the object, and the right hand side will be the name you provide to rename it to.

Here is an example:

javascript rename destructured variable

This comes in really handy if you need to destructure lots of similar objects, like request responses so that you can then name the responses exactly how you want to avoid confusion.

Another use case is within props(react) or arguments provided into functions.

Here is an example of rename destructured argument in JavaScript:

javascript rename destructured variable

How to rename a destructured variable in JavaScript with a default value

Destructuring a variable in JavaScript with a default value can be done in the same way in which you would ordinarily do when looking at arguments in a function.

You will need to set the default using the assignment operator.

Here is an example of how to rename a destructured variable in JavaScript with a default value with an argument:

javascript destructuring rename with default value in argument

And here is an example with a standard variable:

javascript destructuring rename with default value

There we have how to rename a destructured variable in JavaScript, if you want more like this be sure to check out some of my other posts!

Foxi - Budget Planner & Tracker

Budget Planner & Tracker

More money in your pocket by the end of the month.

Free to use and no account needed.

Get started now.

Some graphics used on this post were made using icons from flaticon .

Latest Posts

How to navigate without animations in react native navigation.

How to Navigate Without Animations in React Native Navigation

In this post find out about how to Navigate Without Animations in React Native Navigation

How to Add a Custom Font in React Native

How to Add a Custom Font in React Native

In this post find out about how to Add a Custom Font in React Native

How to Print in JavaScript Console

How to Print in JavaScript Console

In this post find out about how to Print in JavaScript Console

How to Debug in React Native

How to Debug in React Native

In this post find out about how to Debug in React Native

Learn React, JavaScript and TypeScript

Join the platform that top tier companies are using. Master the skills you need to succeed as a software engineer and take your career to the next level with Pluralsight.

Become an expert in ReactJS, TypeScript, and JavaScript.

Here you will find my personal recomendations to you, for full disclosure I earn a small commission from some of these links, but I only recommend what I trust and personally use.

Good things are coming, don't miss out!

Follow me on Twitter to stay up to date and learn frontend, React, JavaScript, and TypeScript tips and tricks!

Are you a novice, intermediate or expert react engineer?

Find out here by taking my fun , interactive, quick quiz which takes approximately 1 - 3 minutes. How well will you will do?

Cracking the Coding Interview graphic

Cracking the Coding Interview

This software engineering book is written by Gayle Laakmann McDowell and is immensely useful if you are looking to learn the skills you need to accelerate your career and land yourself jobs at top tier tech companies such as Google, Facebook, or Microsoft.

You don't know JS yet (YDKJS) graphic

You don't know JS yet (YDKJS)

You don't know JS yet is one of the best, most complete books in the industry if you want to get to know JavaScript in depth.

Introduction to Algorithms graphic

Introduction to Algorithms

An Introduction to Algorithms is pretty popular amongst software engineers because it is one of the best and most complete books you will find on computer algorithms.

Macbook Pro 16" graphic

Macbook Pro 16"

The Macbook Pro is easily the best laptop for frontend development of any kind (and almost all other types of development) and will boost your productivity like never before.

Rename & Destructure Variables in ES6

Rename & Destructure Variables in ES6

Last post we took a look at an intro to destructuring . Let's take a look at another use case which would be renaming your variables. Sometimes data comes back in some odd names, and you might not necessarily want to use a property key as the end variable name. Maybe you don't like that variable name or it's already taken in your scope.

For example here, I already used twitter as a variable. I can't use it again, but I'm stuck, because this object gives me twitter as a key. What you can do is you can rename them as you destructure them.

So - I want the twitter property, but I want to call it tweet. I want the facebook property, but I want to call it fb .

The above code will pull the wes.links.social.twitter into a variable called tweet and similarly fb for facebook .

Find an issue with this post? Think you could clarify, update or add something?

All my posts are available to edit on Github. Any fix, little or small, is appreciated!

Edit on Github

A Dead Simple intro to Destructuring JavaScript Objects

Setting Default Values with JavaScript’s Destructuring

Coding Help Tips Resources Tutorials

Google Apps Scripts and Web Development Tutorials and Resources by Laurence Svekis

js destructuring assignment rename

Mastering JavaScript Destructuring Assignment: A Comprehensive Guide

Destructuring assignment is a powerful feature in JavaScript introduced with ES6 (ECMAScript 2015). It allows you to unpack values from arrays or properties from objects into distinct variables in a more concise and readable manner. This guide will help you understand how to effectively use destructuring assignment in your JavaScript code, complete with examples and best practices.

What is Destructuring Assignment?

Destructuring assignment is a syntax that enables you to unpack values from arrays or objects into individual variables. This can greatly enhance the readability and maintainability of your code.

Destructuring Arrays

Array destructuring lets you extract values from an array into separate variables.

Basic Array Destructuring

const fruits = [‘apple’, ‘banana’, ‘cherry’];

const [first, second, third] = fruits;

console.log(first); // apple

console.log(second); // banana

console.log(third); // cherry

Skipping Items

You can skip items in the array by leaving empty slots.

const [first, , third] = fruits;

Using Rest Operator

The rest operator (…) can be used to collect the remaining elements.

const numbers = [1, 2, 3, 4, 5];

const [first, second, …rest] = numbers;

console.log(first); // 1

console.log(second); // 2

console.log(rest); // [3, 4, 5]

Destructuring Objects

Object destructuring allows you to unpack properties from an object into distinct variables.

Basic Object Destructuring

const person = {

  name: ‘Alice’,

  age: 30,

  city: ‘New York’

const { name, age, city } = person;

console.log(name); // Alice

console.log(age); // 30

console.log(city); // New York

Renaming Variables

You can rename variables while destructuring.

const { name: personName, age: personAge, city: personCity } = person;

console.log(personName); // Alice

console.log(personAge); // 30

console.log(personCity); // New York

Default Values

You can set default values for variables in case the property does not exist in the object.

  age: 30

const { name, age, city = ‘Unknown’ } = person;

console.log(city); // Unknown

Nested Destructuring

Destructuring can be used to extract values from nested objects and arrays.

Nested Object Destructuring

  address: {

    street: ‘123 Main St’,

    city: ‘New York’

  }

const { name, address: { street, city } } = person;

console.log(street); // 123 Main St

Nested Array Destructuring

const numbers = [1, [2, 3], 4, 5];

const [first, [second, third], fourth] = numbers;

console.log(third); // 3

console.log(fourth); // 4

Destructuring Function Parameters

Destructuring is particularly useful for handling function parameters, making the function signatures more readable and flexible.

Destructuring Objects in Function Parameters

function greet({ name, age }) {

  return `Hello, my name is ${name} and I am ${age} years old.`;

console.log(greet(person)); // Hello, my name is Alice and I am 30 years old.

Destructuring Arrays in Function Parameters

function sum([a, b]) {

  return a + b;

const numbers = [5, 10];

console.log(sum(numbers)); // 15

Real-World Example: API Response Handling

Destructuring is extremely useful when dealing with API responses.

const response = {

  status: 200,

  data: {

    user: {

      id: 1,

      name: ‘Alice’,

      email: ‘[email protected]

    }

const { status, data: { user: { id, name, email } } } = response;

console.log(status); // 200

console.log(id); // 1

console.log(email); // [email protected]

Destructuring assignment is a powerful feature in JavaScript that simplifies the process of extracting values from arrays and objects. By mastering destructuring, you can write cleaner, more concise, and more readable code. Practice using destructuring in various scenarios to become proficient in this technique.

Destructuring assignment

The two most used data structures in JavaScript are Object and Array .

  • Objects allow us to create a single entity that stores data items by key.
  • Arrays allow us to gather data items into an ordered list.

However, when we pass these to a function, we may not need all of it. The function might only require certain elements or properties.

Destructuring assignment is a special syntax that allows us to “unpack” arrays or objects into a bunch of variables, as sometimes that’s more convenient.

Destructuring also works well with complex functions that have a lot of parameters, default values, and so on. Soon we’ll see that.

Array destructuring

Here’s an example of how an array is destructured into variables:

Now we can work with variables instead of array members.

It looks great when combined with split or other array-returning methods:

As you can see, the syntax is simple. There are several peculiar details though. Let’s see more examples to understand it better.

It’s called “destructuring assignment,” because it “destructurizes” by copying items into variables. However, the array itself is not modified.

It’s just a shorter way to write:

Unwanted elements of the array can also be thrown away via an extra comma:

In the code above, the second element of the array is skipped, the third one is assigned to title , and the rest of the array items are also skipped (as there are no variables for them).

…Actually, we can use it with any iterable, not only arrays:

That works, because internally a destructuring assignment works by iterating over the right value. It’s a kind of syntax sugar for calling for..of over the value to the right of = and assigning the values.

We can use any “assignables” on the left side.

For instance, an object property:

In the previous chapter, we saw the Object.entries(obj) method.

We can use it with destructuring to loop over the keys-and-values of an object:

The similar code for a Map is simpler, as it’s iterable:

There’s a well-known trick for swapping values of two variables using a destructuring assignment:

Here we create a temporary array of two variables and immediately destructure it in swapped order.

We can swap more than two variables this way.

The rest ‘…’

Usually, if the array is longer than the list at the left, the “extra” items are omitted.

For example, here only two items are taken, and the rest is just ignored:

If we’d like also to gather all that follows – we can add one more parameter that gets “the rest” using three dots "..." :

The value of rest is the array of the remaining array elements.

We can use any other variable name in place of rest , just make sure it has three dots before it and goes last in the destructuring assignment.

Default values

If the array is shorter than the list of variables on the left, there will be no errors. Absent values are considered undefined:

If we want a “default” value to replace the missing one, we can provide it using = :

Default values can be more complex expressions or even function calls. They are evaluated only if the value is not provided.

For instance, here we use the prompt function for two defaults:

Please note: the prompt will run only for the missing value ( surname ).

Object destructuring

The destructuring assignment also works with objects.

The basic syntax is:

We should have an existing object on the right side, that we want to split into variables. The left side contains an object-like “pattern” for corresponding properties. In the simplest case, that’s a list of variable names in {...} .

For instance:

Properties options.title , options.width and options.height are assigned to the corresponding variables.

The order does not matter. This works too:

The pattern on the left side may be more complex and specify the mapping between properties and variables.

If we want to assign a property to a variable with another name, for instance, make options.width go into the variable named w , then we can set the variable name using a colon:

The colon shows “what : goes where”. In the example above the property width goes to w , property height goes to h , and title is assigned to the same name.

For potentially missing properties we can set default values using "=" , like this:

Just like with arrays or function parameters, default values can be any expressions or even function calls. They will be evaluated if the value is not provided.

In the code below prompt asks for width , but not for title :

We also can combine both the colon and equality:

If we have a complex object with many properties, we can extract only what we need:

The rest pattern “…”

What if the object has more properties than we have variables? Can we take some and then assign the “rest” somewhere?

We can use the rest pattern, just like we did with arrays. It’s not supported by some older browsers (IE, use Babel to polyfill it), but works in modern ones.

It looks like this:

In the examples above variables were declared right in the assignment: let {…} = {…} . Of course, we could use existing variables too, without let . But there’s a catch.

This won’t work:

The problem is that JavaScript treats {...} in the main code flow (not inside another expression) as a code block. Such code blocks can be used to group statements, like this:

So here JavaScript assumes that we have a code block, that’s why there’s an error. We want destructuring instead.

To show JavaScript that it’s not a code block, we can wrap the expression in parentheses (...) :

Nested destructuring

If an object or an array contains other nested objects and arrays, we can use more complex left-side patterns to extract deeper portions.

In the code below options has another object in the property size and an array in the property items . The pattern on the left side of the assignment has the same structure to extract values from them:

All properties of options object except extra which is absent in the left part, are assigned to corresponding variables:

Finally, we have width , height , item1 , item2 and title from the default value.

Note that there are no variables for size and items , as we take their content instead.

Smart function parameters

There are times when a function has many parameters, most of which are optional. That’s especially true for user interfaces. Imagine a function that creates a menu. It may have a width, a height, a title, an item list and so on.

Here’s a bad way to write such a function:

In real-life, the problem is how to remember the order of arguments. Usually, IDEs try to help us, especially if the code is well-documented, but still… Another problem is how to call a function when most parameters are ok by default.

That’s ugly. And becomes unreadable when we deal with more parameters.

Destructuring comes to the rescue!

We can pass parameters as an object, and the function immediately destructurizes them into variables:

We can also use more complex destructuring with nested objects and colon mappings:

The full syntax is the same as for a destructuring assignment:

Then, for an object of parameters, there will be a variable varName for the property incomingProperty , with defaultValue by default.

Please note that such destructuring assumes that showMenu() does have an argument. If we want all values by default, then we should specify an empty object:

We can fix this by making {} the default value for the whole object of parameters:

In the code above, the whole arguments object is {} by default, so there’s always something to destructurize.

Destructuring assignment allows for instantly mapping an object or array onto many variables.

The full object syntax:

This means that property prop should go into the variable varName and, if no such property exists, then the default value should be used.

Object properties that have no mapping are copied to the rest object.

The full array syntax:

The first item goes to item1 ; the second goes into item2 , and all the rest makes the array rest .

It’s possible to extract data from nested arrays/objects, for that the left side must have the same structure as the right one.

We have an object:

Write the destructuring assignment that reads:

  • name property into the variable name .
  • years property into the variable age .
  • isAdmin property into the variable isAdmin (false, if no such property)

Here’s an example of the values after your assignment:

The maximal salary

There is a salaries object:

Create the function topSalary(salaries) that returns the name of the top-paid person.

  • If salaries is empty, it should return null .
  • If there are multiple top-paid persons, return any of them.

P.S. Use Object.entries and destructuring to iterate over key/value pairs.

Open a sandbox with tests.

Open the solution with tests in a sandbox.

Lesson navigation

  • © 2007—2024  Ilya Kantor
  • about the project
  • terms of usage
  • privacy policy

Destructure and rename variables with JavaScript, plus other cool JS destructuring use cases

Last updated on: June 12, 2023

Table of Contents

Want to simplify your JavaScript code and extract the values you need from objects and arrays easily? Learn how to use destructuring! In this article, I'll show you how to destructure objects and arrays, rename variables, set default values, and merge arrays and objects. Plus, I'll also cover how to use destructuring in practical scenarios, such as extracting data from APIs and handling function parameters.

Destructuring and Renaming Variables in JavaScript

Destructuring is a useful feature in JavaScript which lets you assign variables to the values of object properties and array items easily. It is a way of unpacking data from objects and arrays into different variables.

This allows you to create new variables from object properties and array items. In JavaScript, you can destructure objects with curly braces and arrays with brackets [].

JavaScript Object Destructuring Syntax

Destructuring can be used in lots of ways, but the most common usage is to extract properties from an object or items from an array.

For objects, the syntax is as follows:

Here, we’re destructuring the person object and assigning its name and age property values to a name and age variable.

Note: Destructuring doesn’t actually change the original object at all. It only copies the value of the object properties.

JavaScript Array Destructuring Syntax

For arrays, the syntax is:

In the example above, we use destructuring to assign the first two items from the numbers array to the first and second variables.

Storing the remaining values in a separate variable

You can use the ... rest operator to assign the remaining properties or items in an array to another variable.

Whatever variable you put the ... rest operator in front of, it will have the rest of the values that you didn’t destructure. It will create a new object when destructuring an object and a new array when destructuring an array.

Renaming variables using destructuring

One of the useful features of destructuring is that it allows you to rename variables during the assignment. You can use the colon : to rename a variable.

For example:

In this example, we are renaming the name property to personName and the age property to personAge . This is useful when you want to rename a property to something more specific or if there is another variable in the current JavaScript scope with the same name.

Note: the right hand-side will be the new name that you want to use, and the left hand-side will be the name of the property you want to destructure. {name: firstName} means {name as firstName}

Default values with destructuring

You can also set default values for variables in case the value is undefined or null. You can do this by using the equal sign = after the variable name.

In this example, if the age property is not defined in the person object, it will default to 30 . This feature is particularly useful when you need to handle optional properties in an object.

Practical examples of destructuring in JavaScript

Destructuring can be used in many practical scenarios such as extracting data from APIs, handling function parameters, and more. Here are a few cool tricks you can do with destructuring in JavaScript.

Extracting function arguments

You can use destructuring to quickly create variables from an object parameter for a function.

In this example, we are using destructuring to extract the firstName and lastName properties from the person object to get the full name. This makes the code more readable, and the function parameter is self-documenting.

Overall, destructuring and renaming variables in JavaScript is a powerful feature that can simplify your code and make it more readable. With destructuring, you can extract the values you need from objects and arrays with ease, and with renaming, you can make your code more descriptive and self-documenting.

Removing some properties from an object

To remove some properties from an object, you can use destructuring and the rest operator.

In this example, we are removing the age property from the person object and creating a new object without it. This can be useful when you want to pass an object to a function, but don’t want to include certain properties.

Merging arrays and objects

Destructuring is also useful when you want to merge objects or arrays. You can use the spread operator to merge objects or arrays together.

Here, we are using the spread operator to merge the person and address objects into a new object. We are also using the spread operator to merge two arrays into a new array. This is a concise way of merging objects and arrays without having to write a lot of code.

Multiple return values

Finally, destructuring can be used to return multiple values from a function.

In this example, we are using destructuring to assign the values returned from the getValues function to the variables a , b , and c . This is a convenient way to return multiple values from a function without having to pack them into an object or array.

If you are using react, then this syntax will be familiar. It is used to destructure the return values of useState and other react hooks.

Here’s an example of using useState with destructuring in a React component:

You clicked {count} times

JavaScript destructuring allows for easy assignment of object properties and array items to variables. Renaming variables, setting default values, and merging arrays and objects are all possible with destructuring. It can be used in practical scenarios such as extracting data from APIs and handling function parameters. Destructuring is also used in React hooks such as useState . What are your favourite ways of using destructuring? Let me know in the comments below.

Related Posts

Migrating my site from next.js to astro, picking simplicity over complexity, how to debug a node.js server, javascript performance testing made easy: a beginner's guide, get the latest posts & updates directly to your inbox.

No span, ever. Unsubscribe at any time

IMAGES

  1. #javascript ES6 cheatsheet

    js destructuring assignment rename

  2. DESTRUCTURING AND SPREAD

    js destructuring assignment rename

  3. Rond dignité Poche javascript object declaration syntax extraterrestre Emprunter Fini

    js destructuring assignment rename

  4. Tip on Destructuring Objects

    js destructuring assignment rename

  5. What is javascript destructuring and different ways to perform destructuring

    js destructuring assignment rename

  6. [JS] Destructuring Assignment

    js destructuring assignment rename

VIDEO

  1. How to use Destructuring assignment in JavaScript

  2. Use Destructuring Assignment to Pass an Object as a Function's Parameters (ES6) freeCodeCamp

  3. 13 Destructuring via rest elements

  4. Practical examples of destructuring of arrays in JavaScript

  5. What is destructuring in typescript/javascript

  6. 🔍🔍 Unpacking Objects: Exploring Destructuring in JavaScript! 🔍🔍 #telugu #codewithkg

COMMENTS

  1. javascript - Destructuring and rename property - Stack Overflow

    You could destructure with a renaming and take the same property for destructuring. const a = { b: { c: 'Hi!' } }; const { b: formerB, b: { c } } = a; console.log(formerB) console.log(c); Share

  2. Destructuring assignment - JavaScript | MDN - MDN Web Docs

    The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

  3. Rename Variables When Using Object Destructuring in JavaScript

    When destructuring an object, you can rename the variables like so: const { first_name: firstName, last_name: lastName } = obj; This is perfect for cases where you want to rename variables from a REST API whose naming conventions don't line up with yours.

  4. javascript - Renaming remaining properties variable when ...

    You can give any other name than other when destructuring variables. For example: const {...rest} = someVaribale; const {...myname} = otherVariable;

  5. JavaScript Object Destructuring Rename: How to Rename Object ...

    Object destructuring rename is a JavaScript feature that allows you to rename the properties of an object when you destructure it. This can be useful for making your code more readable and concise. To use object destructuring rename, you simply need to use the `as` keyword when you destructure an object.

  6. How to rename a destructured variable in JavaScript

    How to rename a destructured variable in JavaScript with a default value. Destructuring a variable in JavaScript with a default value can be done in the same way in which you would ordinarily do when looking at arguments in a function. You will need to set the default using the assignment operator.

  7. Rename & Destructure Variables in ES6 - Wes Bos

    Setting Default Values with JavaScripts Destructuring.

  8. Mastering JavaScript Destructuring Assignment: A ...

    Destructuring assignment is a powerful feature in JavaScript introduced with ES6 (ECMAScript 2015). It allows you to unpack values from arrays or properties from objects into distinct variables in a more concise and readable manner.

  9. Destructuring assignment - The Modern JavaScript Tutorial

    Destructuring assignment allows for instantly mapping an object or array onto many variables. The full object syntax: let {prop : varName = defaultValue, ...rest} = object

  10. rename variables with JavaScript, plus other ...">Destructure and rename variables with JavaScript, plus other ...

    One of the useful features of destructuring is that it allows you to rename variables during the assignment. You can use the colon : to rename a variable. For example: const person = { name: 'John', age: 30 }; const { name: personName, age: personAge } = person;