Wednesday, January 9, 2019

Javascript: Destructuring

Destructuring Objects

With destructuring, you can extract multiple pieces of data at the same time via patterns in locations that receive data.

const person = {
   first: "John",
   last: "Doe",
   links: {
      social: {
         twitter: "https://twitter.com/john.ca",
         facebook: "https://facebook.com/johndoe"
      },
      web: {
         blog: "https://johndoe.com"
      }
   }
};

const { twitter, facebook } = person.links.social;

Rename the variables as you destructure
const { twitter: tweet, facebook: fb } = person.links.social;

Set fallback or default value
const settings = { width: 300, color: "black" };
const { width = 100, height = 100, color = "blue", fontSize = 25 } = settings;

Destructuring arrays

const details = ["John Doe", 123, "johndoe.com"];
const [name, id, website] = details;
console.log(name, id, website);

Destructuring comma separated string

const data = "Basketball,Sports,90210,23,John,Doe,cool";
const [itemName, category, sku, inventory] = data.split(",");

Destructuring into Rest - an example using rest parameter

const team = ["John", "Harry", "Sarah", "Keegan", "Riker"];
const [captain, assistant, ...players] = team;

Swapping Variables with Destructuring

let inRing = "Hulk Hogan";
let onSide = "The Rock";

[inRing, onSide] = [onSide, inRing];

To make order of arguments independent, wrap these 3 arguments in , and then pass an object in tipCalc function so that it destructures the object.

function tipCalc({ total = 100, tip = 0.15, tax = 0.13 }) {
   return total + tip * total + tax * total;
}

const bill = tipCalc({ tip: 0.2, total: 200 });
console.log(bill);

What is we don't pass anything in tipcalc?

function tipCalcDefault({ total = 100, tip = 0.15, tax = 0.13 } = {}) {
   return total + tip * total + tax * total;
}

const newBill = tipCalcDefault();
console.log(newBill);
Share This:    Facebook Twitter

0 comments:

Post a Comment

Total Pageviews

My Social Profiles

View Sonal's profile on LinkedIn

Tags

__proto__ $Browser Access Grants Accessor properties Admin Ajax AllowsCallouts Apex Apex Map Apex Sharing AssignmentRuleHeader AsyncApexJob Asynchronous Auth Provider AWS Callbacks Connected app constructor Cookie CPU Time CSP Trusted Sites CSS Custom settings CustomLabels Data properties Database.Batchable Database.BatchableContext Database.query Describe Result Destructuring Dynamic Apex Dynamic SOQL Einstein Analytics enqueueJob Enterprise Territory Management Enumeration escapeSingleQuotes featured Flows geolocation getGlobalDescribe getOrgDefaults() getPicklistValues getRecordTypeId() getRecordTypeInfosByName() getURLParameters Google Maps Governor Limits hasOwnProperty() Heap Heap Size IIFE Immediately Invoked Function Expression Interview questions isCustom() Javascript Javascript Array jsForce Lightning Lightning Components Lightning Events lightning-record-edit-form lightning:combobox lightning:icon lightning:input lightning:select LockerService Lookup LWC Manual Sharing Map Modal Module Pattern Named Credentials NodeJS OAuth Object.freeze() Object.keys() Object.preventExtensions() Object.seal() Organization Wide Defaults Override PDF Reader Performance performance.now() Permission Sets Picklist Platform events Popup Postman Primitive Types Profiles Promise propertyIsEnumerable() prototype Query Selectivity Queueable Record types Reference Types Regex Regular Expressions Relationships Rest API Rest Operator Revealing Module Pattern Role Hierarchy Salesforce Salesforce Security Schema.DescribeFieldResult Schema.DescribeSObjectResult Schema.PicklistEntry Schema.SObjectField Schema.SObjectType Security Service Components Shadow DOM Sharing Sharing Rules Singleton Slots SOAP API SOAP Web Services SOQL SOQL injection Spread Operator Star Rating stripInaccessible svg svgIcon Synchronous this Token Triggers uiObjectInfoApi Upload Files VSCode Web Services XHR
Scroll To Top