What Is Destructuring Assignment and Its Uses

What is destructuring assignment and its uses?

What is 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.

- MDN

Advantages

A. Makes code concise and more readable.

B. We can easily avoid repeated destructing expression.

Some use cases

1. To get values in variable from Objects,array

let obj = { 'a': 1,'b': {'b1': '1.1'}}
let {a,b,b:{b1}} = obj
console.log('a--> ' + a, '\nb--> ', b, '\nb1---> ', b1)

let obj2 = { foo: 'foo' };
let { foo: newVarName } = obj2;
console.log(newVarName);

let arr = [1, 2, 3, 4, 5]
let [first, second, ...rest] = arr
console.log(first, '\n', second, '\n', rest)

// Nested extraction is possible too:
let obj3 = { foo: { bar: 'bar' } };
let { foo: { bar } } = obj3;
console.log(bar);

What's the difference between object destructuring and normal object assignment in Javascript ES6?

Let's extend this to multiple properties:

var {foo, bar, baz} = user;

In the traditional syntax, this would be:

var foo = user.foo,
bar = user.bar,
baz = user.baz;

So for every property, we have to repeat the object we want to access (user) and the name of the property foo = ... .foo. The new syntax makes it easier to repeat yourself less.

There's another difference if the object isn't already stored in a variable:

var {foo, bar, baz} = getUser();

Now we can't just do

var foo = getUser().foo,
bar = getUser().bar,
baz = getUser().baz;

because each call to getUser might do different things (due to side effects) or just be inefficient (because we're repeating work). We'd have to create a new local variable to store the object in, just to initialize the three variables we actually care about.

Destructuring Assignment to Pass an object as function's parameter

Of course the function doesn't mention stats explicitly - the function cannot know the name of a variable that might be passed to it

const stats = {
max: 56.78,
standard_deviation: 4.34,
median: 34.54,
mode: 23.87,
min: -0.75,
average: 35.85
};

const half = ({ max, min }) => (max + min) / 2.0;

console.log(half(stats));

Destructuring assignment vs using whole object - what about performance?

Accessing object properties does barely take any time in JS. It barely matters if you do this once during destructuring, or multiple times in the template.

So it's just a matter of preference - and a matter of how many properties of the same object you use in the template (your example only ever uses one, but if multiple are used, having a seperate const for every single one kide of bloates the code unnecessarily)

Benefits of destructuring assignments in Javascript

The benefit is that you don't need to repeat the destructured expression. Granted, in your example it hardly makes a difference, as you've already got it neatly in that metadata variable.

But if it is a very complex expression, or something else, you could save an extra variable. For example, compare this function

function example(metadata) {
var englishTitle = metadata.title,
localeTitle = metadata.translations[0].title;
…; // use englishTitle and localeTitle
}

to

function example({title: englishTitle, translations: [{title: localeTitle}]}) {
…; // use englishTitle and localeTitle
}

and it becomes more obvious how declarative it is.

As it is true for every syntactic sugar: apply it only where it sweetens your code.

How do I parse a string to number while destructuring?

Destructuring is just a nice way to unpack properties from objects and arrays and assign them to variables. As the trasnpiled code in the question suggests, any kind of operation is not possible.

One hack would be to create 2 more variables (which don't exist in input) and set the default value to the number equivalent of the previously destrucutred properties:

let input = { latitude: "17.0009", longitude: "82.2108" }

let { latitude, longitude, lat = +latitude, long = +longitude } = input

console.log(typeof latitude, typeof longitude, typeof lat, typeof long)

Why use destructuring here?

The general consensus is that this is a bad example for destructuring, but I've gone too far deep and will still attempt to make sense of it.

By using destructuring, it becomes possible to add additional functions to Person.

For example, Person needs to jump:

const Person = (name) => {
const sayName = () => console.log(`my name is ${name}`)

const jump = () => console.log('I jumped') // new feature

return {sayName, jump} // jump can inserted into the object here and used externally
}

Then, as pointed out in the comments, a much better way to pass Person into Nerd would be to:

const Nerd = (name) => {
// simply create a person and pull out the sayName function with destructuring assignment syntax!
const doSomethingNerdy = () => console.log('nerd stuff')
return {...Person(name) , doSomethingNerdy}
}

Before finally, Nerd can be destructured, and all the functions inside Person and Nerd can be used.

I suppose that's what they're trying to get at.

Must use destructuring state assignment : How to destructure from object and place on property inside object literal

Yes, you can do it through arrow function

console.error('this.state.thing', (obj => obj.thing)(this.state))

Why is this Destructuring assignment usage not working?

Destructure the item being iterated over - which is the first parameter, not the second. (The second is the index being iterated over, which is a number.)

let options = [...document.querySelectorAll("#listado option:checked")].map(({ value }) => value)
console.log(options)
<select id="listado" size="5" multiple>
<option value="Leer" id="aficion-leer">Leer</option>
<option value="Programar" id="aficion-programar" selected>Programar</option>
<option value="Cine" id="aficion-cine">Cine</option>
<option value="Deporte" id="aficion-deporte" selected>Deporte</option>
</select>

why it possible to use destructuring assignment in React Native?

You are right nodejs and iojs do not support ES6 syntax. But react native:

As of version 0.5.0, React Native ships with the Babel JavaScript compiler.

Read more here

That means that there is another transpiler (Babel) at work in the React packager. It converts from ECMAScript 2015 (ES6) to ES5. This allows you to use the ES6 features like: destructuring, computed property keys, classes, arrow functions, block-scoped variables and more.

If you want to use those features in the React (not Native) app, you will need to include Babel in your project.


Edit:

There is no another transpiler.

React and React Native have both switched their respective build systems to make use of Babel. This replaced JSTransform, the source transformation tool that we wrote at Facebook.

More in Deprecating JSTransform and react-tools



Related Topics



Leave a reply



Submit