Javascript destructuring assignment in action

The destructuring assignment has been introduced in ECMAScripts 6 and has now been supported by all the major browsers. Basically what this assignment does is to assign the value on the right hand side to the value which has the same name or property name on the left hand side. For example, we can assign the value of a property within an object to the property value within an object with the same property name on the left hand side as follow.

let {value : x} = {value : 30}

console.log(x) // output 30

This is indeed very convenient and saves us lot of unnecessary lines of code. Besides object, we can also use destructuring assignment on the array as well, below is a full example which uses the destructuring assignment on both the array and object to print out the details of a worker and then calculate his salary and bonus.

let personal = {
		jobTitle({name = 'Bob', age = 33, job = 'software engineer'} = {}, [salary, bonus] = [2000, 1.3]) {
			console.log(name + " is " + age + " and works as a " + job);
			console.log("Monthly income is " + salary + " and bonus is " + bonus * salary + " USD.");

let income = [3000, 1.6];

personal.jobTitle({}, income); // if pass in empty object, the default object will be used

personal.jobTitle({name : 'Jonny', age : 20, job : 'web developer'}); // if pass in empty array, the default array will be used instead

The outcome is as follow…

Bob is 33 and works as a software engineer
Monthly income is 3000 and bonus is 4800 USD.
Jonny is 20 and works as a web developer
Monthly income is 2000 and bonus is 2600 USD.

Take note that we use the equal sign within the jobTitle function to assign the default value to both the object and the array object which will be used if undefined, empty (or no parameter) has been passed into the function.

Leave a Reply

Be the First to Comment!

Notify of