in

timeoddGeeky

Destructuring Assignments in JavaScript

Destructuring Assignment

A destructuring assignment allows mapping data structures directly to objects. For example, if I wanted to return the sum of values and number of keys of an object from a single function:

function sumAndLength(obj) {
let sum = 0;
for (let keyName in obj) {
sum += obj[keyName];
}
return [sum, Object.keys(obj).length];
}
const obj = {
property1: 150,
property2: 200,
property3: 175,
};
let [sum, length] = sumAndLength(obj);
console.log(sum, length);
// 525, 3

This is very useful for simple functions where it is more convenient to return multiple results, but destructuring really becomes useful with object returns. Here is an example request that sends back (very simple) HTTP request data:

function simulateRequest(callback) {
setTimeout(function() {
callback({
statusCode: 200,
body: {
content: 'Request succeeded'
}
});
}, 500);
};
simulateRequest(function(response) {
const {
statusCode: code,
body: {
content: bodyContent
}
} = response;
console.info(code, bodyContent);
// 200 'Request succeeded'
});

This looks strange at first, but is easier to read than 2 separate extracting statements for the 2 variables once you get used to it. Unlike the older seperate extractions, the important parts of the structure of the return object is apparent with just reading the extraction code. The original function or documentation do not need to be viewed.

I covered what I think are the most useful parts of destructuring that I personally used, but there are a few more edge cases you may want to know about.  Destructors are available in every browser except IE (but are available for MS edge).

What do you think?

5 points
UpvoteDownvote

Total votes: 0

Upvotes: 0

Upvotes percentage: 0.000000%

Downvotes: 0

Downvotes percentage: 0.000000%

Written by TimeOdd

TimeOdd is a leading technology media property, dedicated to obsessively profiling startups, reviewing new Internet products, and breaking tech news.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Loading…

TimeOdd Stories - Animal

This animal has eyes behind its heads?

TimeOdd Stories - Roast Chicken

Best Roast Chicken With Vegetable