Showing posts with label Destructuring. Show all posts
Showing posts with label Destructuring. Show all posts

Monday, December 13, 2021

Javascript: sort() and Array destructuring

Take a look at the code below.

At first glance, this looks good. We’re not using let, and we’re not mutating on the original array using something like push. But take a look at the console.log statement. It turns out that the sort method does not create a copy of the original array. Instead, it both mutates on the original array and returns its own array from the method call.

And there are a handful of old Array-methods that do this. Be careful with push, shift, unshift, pop, reverse, splice, sort, and fill. Fortunately, most often we can simply avoid calling these methods at all, to stay out of trouble.

However, there are cases, like using sort, where we have to use a method that mutates the original array, in lack of better options. Array destructuring to the rescue! Whenever these occasions arise, make sure to manually copy the array first, before performing an operation on it. It’s as simple as this.

That [...grades] makes the entire difference.

Share This:    Facebook Twitter

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

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