What sets apart object destructuring from destructuring assignment?

Consider this scenario where we have an object:

let obj = { a: 1, b: 2 }
let { a, b } = obj;
console.log(a, b); // output 1, 2

Now, let's examine a different case where 'a' and 'b' are already initialized:

let obj = { a: 1, b: 2 };
let a = 3, b = 4;
{ a, b } = obj;
console.log(a, b); // error

What sets these two situations apart and causes the second one to result in an error?

Answer №1

It is important to enclose the destructuring assignment within parentheses to differentiate it from a block statement where assignment is not permissible.

Assignment without declaration:

Using round brackets ( ... ) around the assignment statement is mandatory when employing object literal destructuring assignment without a declaration.

{a, b} = {a: 1, b: 2} is considered as invalid standalone syntax, as the {a, b} on the left-hand side is recognized as a block rather than an object literal.

However, ({a, b} = {a: 1, b: 2}) is valid, as well as var {a, b} = {a: 1, b: 2}

NOTE: The expression within your ( ... ) must be preceded by a semicolon to prevent it from being misinterpreted as a function call on the preceding line.

let obj = { a: 1, b: 2 };
let a = 3, b = 4;

({ a, b } = obj);
console.log(a, b); // 1, 2

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Are elements in React Native PanResponder capable of being clicked?

While I have movable panresponders, I also require the ability to click on one for an onPress event. Is it achievable? At present, they are <View> elements. If I attempt to switch them to <TouchableOpacity> or a similar element, it results in ...

The custom confirmation popup is experiencing technical issues

Currently, I am utilizing a plugin to modify the appearance of the confirm popup. Although I have successfully customized the confirm popup, I am encountering an issue where upon clicking the delete icon, the custom confirm popup appears momentarily before ...

What are the steps to update content by referencing an id in the hash URL?

Currently, I am utilizing the following code snippet to extract an ID from the hash URL: var integer = window.location.hash.match(/\d+/) | 0; alert(integer); However, I have encountered an issue where upon using the back button after modifying the U ...

Struggling to align elements in React/JS/M?

My challenge is aligning the elements in the middle of my page. I aim to have 3 elements per row, with n rows depending on the number of "VideoBox" components. It's crucial that these elements fit within the lettering of the P R O F E S S I O N A L ...

Utilizing browser local storage in web development

Currently, I am in the midst of working on an e-commerce platform, a project that holds significant importance for me as it marks my debut into major projects. For the first time, I am delving into the realm of local storage to manage basket data such as q ...

Searching for a deeply nested JSON property with lodash

I am dealing with a JSON API response that has the following structure: [ { title: "top1", sections: [ { section_title: "section1", content: [ { content_title: "title1", content_id: "id1" ...

Navigate to a specific URL path and send properties as arguments in the function for handling events

I am working on a vuetify autocomplete search feature. When a user selects an item, I need to navigate to a specific route and pass some props along. However, my attempts to change the current route without passing props have resulted in errors. Here is w ...

Unexpected Behavior in Angular ES6 Controller As Pattern

Forgive the uninspired title, as I am struggling to articulate my query. I have two nearly identical classes that are exhibiting slight variations in behavior. Additionally, there is a perplexing discrepancy where one class triggers a "this method can be s ...

"An issue arises when using req.body and res.render as the values retrieved are

Encountering an unusual problem - when using req.body to transmit form input to another page, the data is properly displayed when a single word is used in the input field (e.g. "FullName"). However, when there is a space, such as in the example "Full Name" ...

Challenges with optimization in AngularJS and Angular Material

Currently, I am working on an AngularJS application that utilizes 7 Angular Material tabs. One issue I have encountered is a significant amount of animation lag when switching tabs or opening a md-select element. According to Chrome Developer Tools, the fr ...

Creating effective href anchors within an iframe using the `srcdoc` attribute

While loading some HTML content in an iframe using the srcdoc attribute, I encountered an issue where following anchor tag links inside the iframe caused the entire page to load within the iframe instead of scrolling to the linked id. You can see a demons ...

Executing a sequence of jQuery's $.when().then() functions

I am facing challenges in understanding how to properly sequence my functions, especially in relation to the $.when() method. function y() { defer = $.Deferred(); $.when(defer).then(console.log(defer.state())); } y(); <script src="https://ajax.go ...

Avoiding the <br> tag in list items with TinyMCE

I am currently using tinyMCE and I needed to enable the "force_br_newlines: true" option. Without this setting, if I press the "Enter" key twice and check the source code, I only see one <br> tag. However, when I set the option to TRUE, it creates a ...

Errors encountered: Navigation guard causing infinite redirection due to unhandled runtime issue

My Vue3 router is set up with the following routes: export const routes: Array<RouteRecordRaw> = [ { path: "/", name: "Browse Questions", component: HomeView, meta: { access: "canAdmin", }, ...

Is there a way to save a base64 image to an excel file?

I need assistance with exporting Excel Charts from NVd3 using Angularjs. Here is the code I have been trying: (jsfiddle) <button id="myButtonControlID">Export Table data into Excel</button> <div id="divTableDataHolder"> <table> ...

The :first selector examines the parent's parent as a reference point, rather than the immediate

I am facing a challenge with shuffling large elements within my layout because of floating them and attempting to display them. Specifically, the elements with the class .gallery-large always need to be the first child inside the .item container. There are ...

The system is unable to interpret the symbol property 'Symbol(Symbol.iterator)' because it is not defined

I have created a custom .any() method for Array objects to loop through an array and check if any item passes a specified function: Array.prototype.any = (comparator) => { for(let item of this){ if(comparator(item)){ return true ...

How can I utilize the parseFloat feature within my dedicated parseFloat function located in an angular factory?

What is the solution for accessing parseFloat within an angular factory function named parseFloat? angular .module('myApp') .factory('mathService', [MathService]); function MathService() { return { parseFloat: myGl ...

What is the best way to combine several plugins in tinymce?

I experimented with a basic code snippet to test tinyMCE, and everything is functioning properly. However, I encountered an issue when attempting to add multiple plugins simultaneously. In this instance, I utilized the tinymce CDN for reference. Below is ...

Sign up with React: A seamless registration form for

Currently, I am working on integrating a signup feature into my React application Here is a snippet of the code from my signup.JSX file: const Senddata = () => { // if(isvalid.username && // isvalid.password && ...