Practical Use-Cases of Javascript Destructuring Operator

javascript
Published on September 5, 2019

Use-Cases of this Tutorial

  • Know how destructuring can be useful in day to day Javascript programming.

Javascript Destructuring Series

Arrays, other iterables (Set, Map etc), and objects can be destructured and values can be assigned to variables. This opens up interesting possibilities to use destructuring to cut down amount of code. Before we would have written multiple lines of code to do a thing, but with destructuring it all reduces to just a single line of code.

Swapping Variables

With destructuring variables can be swapped without using a third variable.

var a = 5;
var b = 10;

// new array created, then destructured
[a, b] = [b, a];

// 10
console.log(a);

// 5
console.log(b);

You can even swap as many variables as required.

var a = 5;
var b = 10;
var c = 15

[c, b, a] = [b, a, c];

Multiple Return Values from Functions

It is very common to return multiple values from functions. We achieve this by wrapping the required values inside an object or array, and then returning that. Then individual entries of returned array or object are used to assign values to variables.

function myFunc() {
	return {
		id: 1001, 
		name: "John Doe"
	};
}

var data = myFunc();
var id = data['id'];
var name = data['name'];

With destructuring, things become direct.

function myFunc() {
	return {
		id: 1001, 
		name: "John Doe"
	};
}

var { id, name } = myFunc();

Change in Order of Function Parameters

Say we have a function that accepts multiple parameter, and is called from various sections in the code.

Now during a maintenance activity we are asked to changed the order of the parameters. This would require changing function definition, and also function calls.

It would have been much better if we had passed on object containing the fields to this function. On top of that we can use destructuring to choose the fields we require in the function.

function myFunc({ id, name, age }) {
	// create HTML
}

var data = {
	id: 1001,
	name: "John", 
	age: 24,
	bio: "Hi I am John",
	interests: ["swimming", "video games"],
	username: "john21"
};

myFunc(data);

You can also give default values for fields which may not be passed.

function myFunc({ id, name, age = 'NA' }) {
	// create HTML
}

This would make code future-proof, and maintenance time can be reduced.

In this Tutorial