Showing posts with label Rest Operator. Show all posts
Showing posts with label Rest Operator. Show all posts

Wednesday, January 9, 2019

Javascript: Spread and Rest Operators

Rest Operator

Takes multiple things and packs it into a single array

function convertCurrency(rate, ...amounts) {
   console.log(rate, amounts); // 1.5 [10, 20, 30]
}
convertCurrency(1.5, 10, 20, 30);

Can be used while destructuring into an array

const team = ["John", "Kait", "Lux", "Sheena", "Kelly"];
const [captain, assistant, ...players] = team;
console.log(captain, assistant, players);

Spread Operator

(3 dots in-front of an array or any iterable) Takes every single item from an iterable (that can loop over with for-of loop) and spread it into a new array

const featured = ["Deep Dish", "Pepperoni", "Hawaiian"];
const specialty = ["Meatzza", "Spicy Mama", "Margherita"];

const pizzas = [...featured, "veg", ...specialty];

Using above example, creating a new array fridayPizzas

const fridayPizzas = [...pizzas];

pizzas != fridayPizzas (shallow copy)

Spread string
const name = "john";
console.log([...name]); // ["j", "o", "h", "n"]

Remove an object from an array of objects
const comments = [
   { id: 209384, text: "I love your dog!" },
   { id: 523423, text: "Cuuute! 🐐" },
   { id: 632429, text: "You are so dumb" },
   { id: 192834, text: "Nice work on this wes!" }
];
const id = 632429;
const commentIndex = comments.findIndex(comment => comment.id === id);

const newComments = [
   ...comments.slice(0, commentIndex),
   ...comments.slice(commentIndex + 1)
];
console.log(newComments);

Spreading into a function
const inventors = ["Einstein", "Newton", "Galileo"];
const newInventors = ["Musk", "Jobs"];
inventors.push(...newInventors); // and not inventors.push(newInventors);
console.log(inventors);

One more example

const name = ["John", "Doe"];

function sayHi(first, last) {
   alert(`Hey there ${first} ${last}`);
}

sayHi(...name);
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