Destructor ๐Ÿ”จ

Questions ๐Ÿค”
  1. What is destruction?
  2. How do you destruct an array?
  3. How do you destruct an object?
  4. How do you destruct a string?
  5. How do you swap a variable using destruction?
  6. Destructuring Functions - Multiple returns and named defaults :::

Destructing Assignment


Destructuring Assignment is a syntax that allows you to assign object properties or array items as variables.

This can greatly reduce the lines of code necessary to manipulate data in these structures.

Destructing an object {...}

Object destructuring is a bit different because keys are not necessarily in a specific order.

let gadgets = {mobile: '๐Ÿ“ฑ', monitor: '๐Ÿ–ฅ', laptop: '๐Ÿ’ป', printer: '๐Ÿ–จ'};
let {mobile, monitor} = gadgets;
console.log(mobile); // ๐Ÿ“ฑ
console.log(monitor); // ๐Ÿ–ฅ
// Shuffling the order
let {monitor, mobile} = gadgets;
console.log(mobile); // ๐Ÿ“ฑ
console.log(monitor); // ๐Ÿ–ฅ

๐Ÿ”ธ Aliasing the property

It also has the flexibility to Alias a property

let gadgets = {mobile: '๐Ÿ“ฑ', monitor: '๐Ÿ–ฅ', laptop: '๐Ÿ’ป', printer: '๐Ÿ–จ'};
let {mobile: SmartPhone, monitor: LEDMonitor} = gadgets;
console.log(SmartPhone); // ๐Ÿ“ฑ
console.log(LEDMonitor); // ๐Ÿ–ฅ

๐Ÿ”ธ Deep Property pulling

We can also pull a property as deep as we want and we can alias that as well

let gadgets = {smartPhone: {iPhone: '๐Ÿ“ฑ'}, monitor: {ledMonitor: '๐Ÿ–ฅ'}};
let {
smartPhone: {iPhone},
monitor: {ledMonitor: MyMonitor},
} = gadgets;
console.log(iPhone); // ๐Ÿ“ฑ
console.log(MyMonitor); // ๐Ÿ–ฅ

By default, properties that arenโ€™t found will be undefined, just like when accessing properties on an object with the dot or bracket notation.

let gadgets = {mobile: '๐Ÿ“ฑ', monitor: '๐Ÿ–ฅ', laptop: '๐Ÿ’ป', printer: '๐Ÿ–จ'};
let {watch} = gadgets;
console.log(watch); // undefined

๐Ÿ”ธ Assigning Default Value

To avoid the risk of Undefined there is something cool feature i.e we can assign a default value. It's useful for the case where the pulled property evaluates to undefined

let gadgets = {mobile: '๐Ÿ“ฑ', monitor: '๐Ÿ–ฅ', laptop: '๐Ÿ’ป', printer: '๐Ÿ–จ'};
let {watch = 'โŒš๏ธ'} = gadgets;
console.log(watch); // โŒš๏ธ
let key = 'smartPhone';
let {[key]: iPhone} = {smartPhone: '๐Ÿ“ฑ'};
console.log(iPhone); // ๐Ÿ“ฑ

Destructing an array [...]

Array destruction uses square brackets [] and it's very similar to the object destruction

let [developer] = [๐Ÿ‘จ๐Ÿปโ€๐Ÿ’ป];
console.log(developer); // ๐Ÿ‘จ๐Ÿปโ€๐Ÿ’ป

Here also we can follow the default value and get the same result

let [developer] = [];
console.log(developer); // undefined
let [developer = '๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป'] = []; // Assigned a default value
console.log(developer); // ๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป

With an array, we have the additional benefit of skipping element

let occupation = ['๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ”ฌ', '๐Ÿง‘๐Ÿปโ€๐Ÿ’ป', '๐Ÿ‘จ๐Ÿปโ€๐Ÿซ'];
let [, , teacher] = occupation;
console.log(teacher); // ๐Ÿ‘จ๐Ÿปโ€๐Ÿซ

๐Ÿ”ธ Nested Array Destructing

let occupation = [['๐Ÿ‘จ๐Ÿปโ€๐Ÿ’ป', '๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป'], ['๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ”ฌ']];
let [[maleDeveloper, femaleDeveloper], [scientist]] = occupation;
console.log(maleDeveloper);
console.log(femaleDeveloper);
console.log(scientist);

Destructing a "string"

let message = 'Hello to all developer ๐Ÿ‘‹';
let [getOneChar = ''] = message;
console.log(getOneChar); // H

Destructing an function

๐Ÿ”ธ Destructing an function parameter

Destructuring can also be applied on function parameters to extract values and assign them to local variables

let developer = {
name: `Abhin Pai`,
gadgets: ['๐Ÿ“ฑ', '๐Ÿ–ฅ', '๐Ÿ’ป', '๐Ÿ–จ'],
nationality: {india: '๐Ÿ‡ฎ๐Ÿ‡ณ'},
};
function getNameAndAddress({name, nationality: {india}}) {
console.log(`Developer Name is ${name} and he is from ${india}`);
}
getNameAndAddress(developer); // Developer Name is Abhin Pai and he is from ๐Ÿ‡ฎ๐Ÿ‡ณ

๐Ÿ”ธ Returning multiple property

function getNameAndAddress() {
let developer = {
name: `Abhin Pai`,
gadgets: ['๐Ÿ“ฑ', '๐Ÿ–ฅ', '๐Ÿ’ป', '๐Ÿ–จ'],
nationality: {india: '๐Ÿ‡ฎ๐Ÿ‡ณ'},
};
return ({
name,
nationality: {india},
} = developer);
}
var result = getNameAndAddress();
console.log(`Developer Name is ${result.name} and he is from ${result.india}`);

Swapping variables without using any third variable

// Traditional technique
function compute() {
let valueA = 500;
let valueB = 200;
let temp;
if (valueA > valueB) {
temp = valueA;
valueA = valueB;
valueB = temp;
}
console.log(valueA); // 200
console.log(valueB); // 500
}
compute();
// Smart way with Destructing
function compute() {
let valueA = 500;
let valueB = 200;
[valueA, valueB] = [valueB, valueA];
console.log(valueA); // 200
console.log(valueB); // 500
}
compute();

๐Ÿ˜ you can see a drastic amount of logic and number of lines is being reduced

Destructing import statement Even though import statements donโ€™t follow destructuring rules, they behave a bit similarly. Whenever youโ€™re writing module import statements, you can pull just what you need from a moduleโ€™s public API

import {pureComponent, component} from react;

import statements have different syntax. When compared against destructuring, none of the following import statements will work

  • Use defaults values such as import {pureComponent = component} from react
  • Deep destructuring style like import {component: { someOtherComponent }} from react is not possible
  • Aliasing syntax import {pureComponent = component} from react :::

Spread Operator


Spread syntax (...) is another helpful addition to JavaScript for working with arrays, objects, and function calls.

The spread allows objects and iterables (such as arrays) to be unpacked, or expanded, which can be used to make shallow copies of data structures to increase the ease of data manipulation

Spear unpack an array or object

Spread with Arrays

Spread can simplify common tasks with arrays like concatenating or some other array manipulation

// Traditional way to concatenating an array
let animals = ['๐ŸฆŠ', '๐Ÿป', '๐Ÿผ', '๐Ÿฏ', '๐Ÿฆ'];
let birds = ['๐Ÿฆ†', '๐Ÿ”', '๐Ÿง', '๐Ÿฆ', '๐Ÿค'];
let leavingBeings = animals.concat(birds);
console.log(leavingBeings); //["๐ŸฆŠ", "๐Ÿป", "๐Ÿผ", "๐Ÿฏ", "๐Ÿฆ", "๐Ÿฆ†", "๐Ÿ”", "๐Ÿง", "๐Ÿฆ", "๐Ÿค"]
// Concatenating with spread operator
let leavingBeings = [...animals, ...birds];
console.log(leavingBeings); //["๐ŸฆŠ", "๐Ÿป", "๐Ÿผ", "๐Ÿฏ", "๐Ÿฆ", "๐Ÿฆ†", "๐Ÿ”", "๐Ÿง", "๐Ÿฆ", "๐Ÿค"]

You can also use a spread operator with an array.

let animals = [{tiger: '๐Ÿฏ'}, {lion: '๐Ÿฆ'}];
let updateAnimal = [...animals, {wolf: '๐ŸฆŠ'}];
console.log(updateAnimal); // [ {tiger: "๐Ÿฏ"}, {lion: "๐Ÿฆ"}, {wolf: "๐ŸฆŠ"}]

Spread can also be used to convert a set, or any other iterable, or String to an Array.

// Converting set into an array
let animals = new Set();
animals.add('Lion');
animals.add('Tiger');
animals.add('Wolf');
console.log(...animals); // [Lion, Tiger, Wolf]
// Converting an string to an array
let animalName = 'Lion';
console.log(...animalName); // ['L', 'i', 'o', 'n']

Spread with Object

When working with objects, the spread can be used to shallow copy and update objects.

// Copying object with Object.Assign();
let animals = {tiger: '๐Ÿฏ', lion: '๐Ÿฆ'};
let copyAnimal = Object.assign({}, animals);
console.log(copyAnimal); // {tiger: "๐Ÿฏ", lion: "๐Ÿฆ"}
// Copy using spread operator
let copyAnimal = {...animals};
console.log(copyAnimal); // {tiger: "๐Ÿฏ", lion: "๐Ÿฆ"}

Adding new property into an existing property

let developer = {
name: `Abhin Pai`,
gadgets: ['๐Ÿ“ฑ', '๐Ÿ–ฅ', '๐Ÿ’ป', '๐Ÿ–จ'],
nationality: {india: '๐Ÿ‡ฎ๐Ÿ‡ณ'},
};
let userInfo = {...developer, blog: 'www.abhinpai.github.io'};
console.log(userInfo); // {name: "Abhin Pai", gadgets: Array(4), nationality: {โ€ฆ}, blog: "www.abhinpai.github.io"}

One important thing to note with updating objects via spread is that any nested object will have to be spread as well

let developer = {
name: `Abhin Pai`,
gadgets: ['๐Ÿ“ฑ', '๐Ÿ–ฅ', '๐Ÿ’ป', '๐Ÿ–จ'],
nationality: {india: '๐Ÿ‡ฎ๐Ÿ‡ณ'},
};
let userInfo = {...developer, gadgets: {smartWatch: 'โŒš๏ธ'}};
console.log(userInfo); // {name: "Abhin Pai", gadgets: {smartWatch: 'โŒš๏ธ'}, nationality: {โ€ฆ}}

In the above example, I tried to add smart-watch into existing gadget object but guess what it overwrites with the new value and we lost the original content

To achieve our result we can spread the inner object as well

let developer = {
name: `Abhin Pai`,
gadgets: ['๐Ÿ“ฑ', '๐Ÿ–ฅ', '๐Ÿ’ป', '๐Ÿ–จ'],
nationality: {india: '๐Ÿ‡ฎ๐Ÿ‡ณ'},
};
let userInfo = {
...developer,
gadgets: {smartWatch: 'โŒš๏ธ', ...developer.gadgets},
};
console.log(userInfo); // {name: "Abhin Pai", gadgets: {โ€ฆ}, nationality: {โ€ฆ}}

Spread with function

We can also take advantage of spread operator in the function

let developer = [
{name: `Abhin Pai`},
{gadgets: ['๐Ÿ“ฑ', '๐Ÿ–ฅ', '๐Ÿ’ป', '๐Ÿ–จ']},
{nationality: {india: '๐Ÿ‡ฎ๐Ÿ‡ณ'}},
];
function printUser(name) {
console.log(name); // Abhin Pai
}
printUser(...developer);

Rest Operator


The syntax of the rest parameter is same as spread i.e ... but rest do have the opposite effect

Rest pack an array or object by creating an array of an indefinite number of arguments.

function gadgets(...args) {
console.log(args); // ["๐Ÿ“ฑ", "๐Ÿ–ฅ", "๐Ÿ’ป", "๐Ÿ–จ"]
}
gadgets('๐Ÿ“ฑ', '๐Ÿ–ฅ', '๐Ÿ’ป', '๐Ÿ–จ');

Rest syntax can be used as the only parameter or as the last parameter in the list. If used as the only parameter, it will gather all arguments, but if it's at the end of a list, it will gather every argument that is remaining.

function gadgets(mobile, monitor, ...args) {
console.log(args); // ["๐Ÿ’ป", "๐Ÿ–จ"]
console.log(mobile); // ๐Ÿ“ฑ
console.log(monitor); // ๐Ÿ–ฅ
}
gadgets('๐Ÿ“ฑ', '๐Ÿ–ฅ', '๐Ÿ’ป', '๐Ÿ–จ');
  • One can't use rest in between parameter which will throw an exception
function gadgets(...args, mobile) {
console.log(args); // SyntaxError: Rest parameter must be last formal parameter
}
gadgets("๐Ÿ“ฑ", "๐Ÿ–ฅ", "๐Ÿ’ป", "๐Ÿ–จ");
  • Older code, the arguments variable could be used to gather all the arguments passed through to which is not possible now with rest
function gadgets() {
console.log(arguments); // Arguments(4) ["๐Ÿ“ฑ", "๐Ÿ–ฅ", "๐Ÿ’ป", "๐Ÿ–จ", callee: ฦ’, Symbol(Symbol.iterator): ฦ’]
}
gadgets('๐Ÿ“ฑ', '๐Ÿ–ฅ', '๐Ÿ’ป', '๐Ÿ–จ');
Last updated on by krishnaUIDev