New Batch#100 (10th Nov 2021) - Salesforce Admin + Dev Training (WhatsApp: +91 - 8087988044) :https://t.co/p4F3oeQagK

Friday, 30 July 2021

JavaScript String Methods

// Strings
const certification = 'JavaScript Developer';
const type = 'Dev';
console.log(type[0]);
console.log(type[1]);
console.log(type[2]);
console.log(certification.length);
console.log('Dev'.length);
console.log(certification.indexOf('a'));
console.log(certification.lastIndexOf('a'));
console.log(certification.indexOf('Dev'));
console.log(certification.slice(11));
console.log(certification.slice(11,14));
console.log(certification.slice(0,certification.indexOf(' ')));
console.log(certification.slice(certification.lastIndexOf(' ') + 1));
console.log(certification.slice(-3));
console.log(certification.slice(1,-1));
// Lower Case, Upper Case and Trim
console.log(certification.toLowerCase());
console.log(certification.toUpperCase());
console.log(certification.toUpperCase().trim());
// Replacing
const desc = 'I am a developer. I am working from 10 years.';
console.log(desc.replace('10','15').replaceAll('.',';'));
// Regular expression to replace all the occurances
console.log(desc.replace(/am/g,'was'));
// Regular expressions should in / and g stands for global
// Replace method is case sensitive
// Booleans
console.log(desc.includes('am'));
console.log(desc.includes('was'));
console.log(desc.startsWith('I'));
console.log(desc.endsWith('.'));
// Split
console.log(desc.split(' '));
const [firstName, lastName] = 'Srinu SFDC'.split(' ');
// join
const myName = ['Mr.', firstName, lastName].join(' ');
console.log(myName);
// Padding
console.log(myName.padStart(20,'*').padEnd(30,'*'));
const maskCard = function(cardNum) {
const str = String(cardNum);
const lastDigits = str.slice(-4);
return lastDigits.padStart(str.length,'*');
}
console.log(maskCard(90989098564578765));
// Repeat
console.log('Flight is dealyed for 1 hour.............'.repeat(6));

Tuesday, 27 July 2021

JavaScript Set and Map

// ES6: Sets and Maps
// Sets
const certifications = new Set([
'Admin', 'PD I', 'PD II', 'Admin', 'AppBuilder'
]);
console.log(certifications);
console.log(certifications.size); // It should be size not length
// Verify value
console.log(certifications.has('Admin'));
console.log(certifications.has('Sales Cloud'));
// Adding Values
certifications.add('Salesforce CPQ')
console.log(certifications);
// Deleting values
certifications.delete('Salesforce CPQ')
console.log(certifications);
// Iteration
for(const cer of certifications) console.log(cer);
// Clear all the values
certifications.clear();
console.log(certifications);
// *** Making Array as Set with the unique values
const names = ['Mark', 'Steve', 'Mark', 'Bob'];
const uniqueNames = [...new Set(names)];
console.log(uniqueNames);
// size of array with unique values
console.log(new Set(['Mark', 'Steve', 'Mark', 'Bob']).size);
// Size of a string with unique characters
console.log(new Set('Steve').size);
--Maps----------------
// Maps are like objects but map keys can be any data type (object keys always should be string)
const resMap = new Map();
resMap.set('firstName', 'Srinu');
resMap.set(1, 'Admin');
console.log(resMap.set(2, 'Dev'));
resMap
.set('certifications',['Admin','PD I'])
.set('city','Bangalore')
.set(true,'He is a Trainer.');
console.log(resMap.get('firstName'));
console.log(resMap.get(resMap.get('firstName') === 'Srinu'));
console.log(resMap.has('lastName'));
resMap.delete('city');
console.log(resMap);
console.log(resMap.size);
resMap.clear();
console.log(resMap);
// resMap.set([1,2],'nums'); // won't work
// console.log(resMap.get([1,2])); // won't work
const myArr = [1,2];
resMap.set(myArr,'nums');
console.log(resMap.get(myArr));
// Map Iteration (Map entries are set of arrays)
const question = new Map([
['question', 'Which is the #1 CRM Platform?'],
[1, 'Microsoft'],
[2, 'Salesforce'],
[3, 'Zoho'],
['correct', 2],
[true, 'Correct'],
[false, 'Try Again']
]);
console.log(question);
const workTimings = {
tue : {
startTime : 0,
endTime : 8,
},
wed : {
startTime : 8,
endTime : 4,
},
thu : {
startTime : 8,
endTime : 4,
},
fri : {
startTime : 8,
endTime : 4,
}
};
// Converting Object to map
console.log(Object.entries(workTimings));
const timingsMap = new Map(Object.entries(workTimings));
console.log(timingsMap);
// Question Iteration
console.log(question.get('question'));
for(const [key,value] of question) {
if(typeof key === 'number') console.log(`Answer ${key}: ${value}`);
}
//const answer = Number(prompt('Enter Answer'));
const answer = 2;
console.log(answer);
console.log(question.get(question.get('correct') === answer));
// convert map to array
console.log([...question]);
console.log([...question.keys()]);
console.log([...question.values()]);
--When to choose which collection -----------------------
Data Structures -
1. Arrays or Sets --> Simple List
2. Objects or Maps --> Key/Value Pair
* Set is faster than Array
* Map is faster than Object
* For Json we use objects

JavaScript Optional Chaining ?. and Loop Object Keys and Values

// Optional Chaining ?.
const resource = {
firstName : 'Srinu',
lastName : 'SFDC',
workTimings : {
tue : {
startTime : 0,
endTime : 8,
},
wed : {
startTime : 8,
endTime : 16,
},
thu : {
startTime : 8,
endTime : 16,
},
fri : {
startTime : 8,
endTime : 16,
}
}
};
console.log(resource.workTimings.mon); // undefiend
//console.log(resource.workTimings.mon.startTime); // error
console.log(resource.workTimings?.mon?.startTime); // Avoid error using Optional chaining
const days = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];
for(const day of days) {
// const working = resource.workTimings[day]?.startTime || 'Not Working';
// 0 to avoid treat as not working use nullish coalescing
const working = resource.workTimings[day]?.startTime ?? 'Not Working';
console.log(`On ${day}, start working from ${working}`)
}
// Method exists
console.log(resource.addCertification?.('Admin') ?? 'Method does not exists');
// Arrays
const resources = [];
console.log(resources[0]?.firstName ?? 'No Resources');
----------------------------------
// Looping Objects Keys and Values
const workTimings = {
tue : {
startTime : 0,
endTime : 8,
},
wed : {
startTime : 8,
endTime : 4,
},
thu : {
startTime : 8,
endTime : 4,
},
fri : {
startTime : 8,
endTime : 4,
}
};
// property Names
const keys = Object.keys(workTimings);
console.log(keys);
// Property Values
const values = Object.values(workTimings);
console.log(values);
// Property Object
const entries = Object.entries(workTimings);
// Destructuring to get the values
for(const [key, {startTime, endTime}] of entries) {
console.log(key,startTime,endTime);
}
-------------------------------------

Monday, 26 July 2021

JavaScript For of loop and Enhanced Object Literals

// for of loop
const certifications = ['Admin', 'PD I', 'PD II'];
for(const certification of certifications) console.log(certification);
// continue and break will still work
for(const certification of certifications.entries()) {
console.log(certification);
console.log(certification[0],certification[1]);
}
console.log([...certifications.entries()]); // Each element as array
// Use destructuring
for(const [i,item] of certifications.entries()) {
console.log(i,item);
}
-------------------------
// Enhanced Object literals
const certifications = ['Admin','PD I','PD II', 'Application Architect'];
const trailblazer = {
name : 'Srinu',
certifications : certifications,
trailhead : {
badges : 115,
points : 90725,
trails : 6
},
addCertification : function(certification) {
console.log(certification);
}
};
console.log(trailblazer);
const trailblazer2 = {
name : 'Srinu',
// Enhanced Object Literals - property name
certifications,
trailhead : {
badges : 115,
points : 90725,
trails : 6
},
// Enhanced Object Literals - function
addCertification(certification) {
console.log(certification);
}
};
console.log(trailblazer2);
const weekdays = ['mon', 'tue', 'wed', 'thu', 'fri'];
const classTimings = {
mon : {
startTime : '9:45 pm',
endTime : '10:15 pm'
},
tue : {
startTime : '9:45 pm',
endTime : '10:15 pm'
},
wed : {
startTime : '9:45 pm',
endTime : '10:15 pm'
},
thu : {
startTime : '9:45 pm',
endTime : '10:15 pm'
},
fri : {
startTime : '9:45 pm',
endTime : '10:15 pm'
}
};
console.log(classTimings);
// Dynamic property names
const classTimings2 = {
[weekdays[0]] : {
startTime : '9:45 pm',
endTime : '10:15 pm'
},
[weekdays[1]] : {
startTime : '9:45 pm',
endTime : '10:15 pm'
},
[`day-${1 + 1}`] : {
startTime : '9:45 pm',
endTime : '10:15 pm'
},
thu : {
startTime : '9:45 pm',
endTime : '10:15 pm'
},
fri : {
startTime : '9:45 pm',
endTime : '10:15 pm'
}
};
console.log(classTimings2);

JavaScript Short Circuiting and Nullish Coalescing

// Short Circuiting
// || or && can be used with any data type and return any data type
// || operator --> first trusty value is returned
// considers the first truthy value
console.log(100 || 'Srinu'); // 100
console.log('' || 'Srinu'); // Srinu
console.log(true || 0); // true
console.log(undefined || null); // null
console.log(undefined || 0 || '' || 'Test' || 10 || null); // Test
// Ternary Operator
const num = 100;
const minNum = num ? num : 10;
console.log(minNum)
// Short Circuiting instead of ternary operator
const minNum2 = num || 10;
console.log(minNum2);
// num is 0 the above 2 approaches won't work
// Use nullish coalescing
let minNum3 = 0;
minNum3 = minNum3 ?? 10;
console.log(minNum3);
// && operator --> first falsy value is returned
console.log(0 && 'Srinu'); // 0
console.log(10 && 'Srinu'); // Srinu
console.log('Hi' && 10 && null && 'Srinu'); // null
// if cond
if(num) {
console.log(num);
}
// Alternative to if cond
num && console.log(num);

JavaScript REST Pttern

// Spread due to the right hand side of =
const myArray = [1,2, ...[3,4]];
// Rest due to the left hand side of = --> To pack or compress
const [a, b, ...others] = [1, 2, 3, 4];
console.log(a, b, others);
const trailblazer = {
name : 'Srinu',
address : {
state : 'Karnataka',
country : 'India'
},
certifications : ['Admin','PD I','PD II', 'Application Architect'],
trailhead : {
badges : 115,
points : 90725,
trails : 6
},
addCertification : function({month, year}) {
console.log(month,year);
}
}
// Rest Pttern should be always last
const [admin, pd1,...otherData] =[...trailblazer.certifications,...others];
console.log(admin,pd1,otherData);
// Objects
const {badges,...restTrailHead} = trailblazer.trailhead;
console.log(restTrailHead);
// functions
const add = function(...numbers) {
console.log(numbers); // compress all the values
let tot = 0;
for(let i = 0; i < numbers.length; i++) {
tot += numbers[i];
}
console.log(sum);
}
add(2,3,5);
add(2,3,5,7); // Seperate values can be supplied
const nums = [90, 20, 20];
add(...nums); // Packaged values can be supplied
// Main elemement and rest of the elemement
const substract = function(mainNum,...numbersToSubstract) {
console.log(mainNum);
console.log(numbersToSubstract);
}
substract(100,10,2,4,5);

Sunday, 25 July 2021

JavaScript Regular Functions vs. Arrow Functions and Primitives vs. Non Primitives

// Diff b/w Regular Functions and Arrow Functions
// Arrow function won't be having it's own this keyword, it is depending on the parent
var firstName = 'Srinu'; // It will be available in window object
const resource = {
firstName : 'Srinu',
lastName : 'SFDC',
year : 1993,
greet : () => {
console.log(this);
console.log(`Hello ${this.firstName}`);
},
calcAge : function() {
console.log(this);
const self = this;
// Inner function won't be having the this keyword
const isNewGeneration = function() {
console.log(self);
console.log(self.year);
}
isNewGeneration();
// When you use arrow function it gets the parent this avoid issue without using self
const isNewGeneration2 = () => {
console.log(this);
console.log(this.year);
}
isNewGeneration2();
}
}
resource.greet();
resource.calcAge();
// Conclusion: Avoid using var and avoid using arrow function if you don't want to think about this keyword.
---
// arguments keyword is present in regular functions
const add = function(n1, n2) {
console.log(arguments);
return n1 + n2;
}
add(10,20);
add(20,40,90);
// arguments keyword is not present in arrow functions
const substract = (n1,n2) => {
console.log(arguments);
return n1 - n2;
}
substract(20,5);
substract(20,5,10);
--------------
// Primitives vs. Non Primitives
// Primitive Types
let age = 20;
let oldAge = age;
age = 21;
console.log(age);
console.log(oldAge);
// Reference Types
const resource = {
name : 'Srinu',
age : 20
}
const sfdcResource = resource; // constant propery values can be changed
sfdcResource.name = 'SFDc';
console.log('resource: ',resource);
console.log('sfdcResource: ',sfdcResource);
sfdcResource = {}; // this won't work as it is const
// Copying Objects
const resource2 = {
name : 'Srinu',
age : 20,
certifications : ['Admin', 'PD I', 'App Builder']
}
const resource2Copy = Object.assign({},resource2);
resource2Copy.name = 'SFDC';
resource2Copy.certifications.push('PD II'); // Deep clone won't work
console.log(resource2,resource2Copy);

JavaScript DOM and Events

Enter ! and presss enter to generate the html snippet.
DOM Reference -
https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ5HQnBCnnCA-SWoVeTZifIaagpZNTGIOLXjw&usqp=CAU
* DOM is not javaScript
* document.queryLocator() --> is part of web apis (libraries browser implement)
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Workshop</title>
<style>
.heading {
color:blue;
}
.button {
background-color: #4CAF50;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
.elmt-color {
color:yellow;
}
.elmt-font {
font-style: italic;
}
</style>
</head>
<body>
<h1 class="heading">JavaScript Example</h1>
<h2>Playing with DOM</h2>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="Srinu"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
<br/>
<input type="button" class="button" value="Input Button"><br/>
<ul>
<li>Aura</li>
<li>LWC</li>
<ul>
<script>
console.log(document.querySelector('.heading').textContent);
document.querySelector('.heading').textContent = 'JavaScript Workshop';
console.log(document.querySelector('#fname').value);
document.querySelector('#lname').value = 'SFDC';
document.querySelector('.button').addEventListener('click',function() {
console.log(`${document.querySelector('#lname').value}`);
});
// To change the background color
document.querySelector('body').style.backgroundColor = 'blue'; // background-color should be backgroundColor
// querySelectorAll
const liElmts = document.querySelectorAll('li');
console.log(liElmts);
for(let i = 0; i < liElmts.length; i++) {
liElmts[i].textContent = liElmts[i].textContent + ' Modified';
}
// Playing with class list
const h2Elmt = document.querySelector('h2');
console.log(h2Elmt);
h2Elmt.classList.add('elmt-font');
h2Elmt.classList.add('elmt-color');
h2Elmt.classList.remove('elmt-font');
// To display or hide
console.log(h2Elmt.style.display);
h2Elmt.style.display = 'block'
console.log(h2Elmt.style.display);
// to listen to the keyboard events
document.addEventListener('keydown',function(e) {
console.log(e.key);
});
</script>
</body>
</html>

Thursday, 22 July 2021

JavaScript Loops

// Looping Stmts
for(let i = 0; i < 10; i++) {
console.log(i);
}
// Looping Array
const myArray = [
'Srinu',
'SFDC',
34,
['Admin','PD1'],
'Salesforce Architect'
];
const indexes = [];
for(let i = 0; i < myArray.length; i++) {
console.log(myArray[i], i);
// indexes[i] = i;
indexes.push(i);
}
console.log(indexes);
// Using continue
for(let i = 0; i < myArray.length; i++) {
if(typeof myArray[i] !== 'string') continue;
console.log(myArray[i], i);
}
// Using break
for(let i = 0; i < myArray.length; i++) {
if(typeof myArray[i] === 'string') break;
console.log(myArray[i], i);
}
// while loop

JavaScript Objects

// To hold unordered / unstructured data
const resource = {
firstName : 'Srinu',
lastName : 'SFDC',
birthYear : 1987,
//calcAge : function(birthYear) {
//return 2021 - birthYear;
//},
//calcAge : function() {
//console.log(this);
//return 2021 - this.birthYear;
//},
calcAge : function() {
this.age = 2021 - this.birthYear;
return this.age;
},
designation : 'Salesforce Architect',
certifications: ['Admin','PD1','PD2','App Builder'],
getDetailInfo : function() {
return `${this.firstName} is a ${this.designation} with the age ${this.calcAge()} and this resource is having ${this.certifications.length} certifications.`;
}
};
console.log(resource.getDetailInfo());
console.log(resource.calcAge())
console.log(resource.age);
//console.log(resource.calcAge());
//console.log(resource.calcAge(1993));
//console.log(resource['calcAge'](1987));
// Dot and Bracket notation
console.log(resource.firstName);
console.log(resource['lastName']);
const selected = prompt('Choose firstName or lastName or age or designation or certifications');
if(resource[selected]) {
console.log(resource[selected]);
}
resource.city = 'Bangalore';
resource['country'] = 'India';
console.log(resource);

JavaScript Arrays

// Arrays
const certifications = ['Admin','PD1','PD2'];
console.log(certifications);
const versions = new Array('WI21','SP21','SU21');
console.log(versions);
// To add the element at last index
const length = certifications.push('CPQ'); // returns the length
console.log(certifications);
console.log(length);
// To add the element at the begining of the index
certifications.unshift('App Builder'); // returns the length
console.log(certifications);
// To remove the last element from array
const removedCer = certifications.pop(); // returns the removed element
console.log(removedCer);
console.log(certifications);
// To remove the first element from array
const removedCer2 = certifications.shift(); // returns the removed element
console.log(removedCer2);
console.log(certifications);
// Identify index based on the value
console.log(certifications.indexOf('PD1')); // -1 if the element is not there
// ES6 includes returns true or false (strict equality)
// Slice won't modify the existing array
const clouds = ['sales', 'service', 'marketing', 'digitalExperience', 'health'];
console.log(clouds.slice(2));
// expected output: Array ['marketing', 'digitalExperience', 'health']
console.log(clouds.slice(2, 4));
// expected output: Array ['marketing', 'digitalExperience']
console.log(clouds.slice(1, 5));
// expected output: Array ['service', 'marketing', 'digitalExperience', 'health']
console.log(clouds.slice(-2));
// expected output: Array ['digitalExperience', 'health']
console.log(clouds.slice(2, -1));
// expected output: Array ['marketing', 'digitalExperience']
// Splice modify the exiting array
//splice(start)
//splice(start, deleteCount)
//splice(start, deleteCount, item1)
//splice(start, deleteCount, item1, item2, itemN)
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 2, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "June"]
months.splice(4, 1, 'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]

Wednesday, 21 July 2021

JavaScript Functions for Salesforce

'use strict'; // Avoid using variables without the declartaion
val = 'test';
console.log(val); // You see error
---
// Functions
function fn() {
console.log('Inside fn');
}
// Calling function
fn();
console.log(calculateBill(500,5)); // This will work as soon as it is declrated atleast later
// Function Declartaion
function calculateBill(billAmount, numOfGuys) {
let billStmt = `Each guy bill is ${billAmount}. Total bill for ${numOfGuys} guys is ${billAmount * numOfGuys}`;
return billStmt;
}
console.log(calcBill(799,5)); // This won't work due to hoisting
// Function Expression - This is better to use
const calcBill = function(billAmount, numOfGuys) {
return billAmount * numOfGuys;
}
// Function Expression
const calcAge1 = function(birthYear) {
return 2021 - birthYear;
}
// ES6 - Arrow Function
const calcAge2 = birthYear => 2021 - birthYear;
console.log(calcAge1, calcAge2);
const isEligible4License = birthYear => {
const age = 2021 - birthYear;
const isTrue = (age >=18 ? true : false);
return isTrue
}
console.log(isEligible4License(30));
const calcBill2 = (billAmount, numOfGuys) => billAmount * numOfGuys;
console.log(calcBill2(799,5));
// Calling a function from the another function
const calcBill3 = (billAmount, numOfGuys) => calcBill(billAmount, numOfGuys);
console.log(calcBill3(799,5));

Monday, 19 July 2021

JavaScript Basics, Operators and Conditional Statements for Salesforce

JavaScript Basics -
javaScript can be used for -
Front End Applications -
Angular JS ...
Back End Applications -
Node JS
javaScript works for both Mobile and Web Apps
ES6 (2015) onwards new version introduced for every year. (ES6 Major update to JavaScript)
To include in the html or visualforce -
<script src="script.js"></script>
Shortcut to open the javaScript console -
Option + Command + j in Mac
Ctrl + Alt + J in Windows
console.log('print here'); // to print in the javaScript console
JavaScript Data Types -
1. Number
2. String
3. Boolean
4. Undefined
5. Null
6. Symbol
7. Bigint
Operators -
const num = 2;
console.log(num + 2, num - 2, num / 2, num ** 3);
const firstName = 'Srinu', lastName = 'SFDC';
console.log(firstName + ' ' + lastName);
// Templace Strings
console.log(`${firstName} ${lastName}`);
== and ===
falsy values: 0, '', undefined, null, NAN
console.log(Boolean(0));
// Assignment Operator -
let num = 5;
// Arthematic Operators
// Unary Operator
num++;
console.log('num: '+num);
// Binary Operator
console.log(num + 5 - (8 - 7), num - 5, num * 5, num / 5, num ** 3);
// Ternary Operator
// Stmt
num > 0 ? console.log('num is > 0') : console.log('num is < 0');
// expression
num = 'num is ' + (num > 0 ? '> 0' : '< 0');
console.log('num: '+num);
Type Conversion and Coercion -
// type coversion
console.log(Number('20')+5);
console.log(Number('test')); //NAN
console.log(String(10));
// automatic type coercion
console.log('I am having ' + 15 + ' certifications ' ); // number will be converted to text , + operator to alway number
console.log('20'-'10');
console.log('20'/'10');
console.log('20'>'10');
conditional statement -
if() {}
else {}
----------------
Only equality -
===============
let day = 'Wedensday';
switch(day) {
case 'Sunday':
console.log(`This is Sunday`);
case 'Monday':
console.log(`This is Monday`);
case 'Tuesday':
console.log(`This is Tuesday`);
break;
case 'Wednesday':
case 'Thrusday':
console.log(`This is Wednesday or Thrusday`);
break;
case 'Friday':
console.log(`This is Friday`);
break;
case 'Saturday':
console.log(`This is Saturday`);
break;
default:
console.log(`Invalid Day`);
}

Friday, 16 July 2021

JavaScript Spread Operator for Salesforce

// Spread Operator - Seperate the array as multiple values
const myArray = [10, 20, 30];
const myNewArray = [0, 5, ...myArray];
console.log(myNewArray); // [ 0, 5, 10, 20, 30 ]
console.log(...myArray); // 10 20 30
const trailblazer = {
name : 'Srinu',
address : {
state : 'Karnataka',
country : 'India'
},
certifications : ['Admin','PD I','PD II', 'Application Architect'],
trailhead : {
badges : 115,
points : 90725,
trails : 6
},
addCertification : function({month, year}) {
console.log(month,year);
},
addCertifications : function(cert1, cert2, cert3) {
console.log(`New certifications: ${cert1} | ${cert3} | ${cert3}`);
}
}
// Creating new array with additional value.
const latestCertifications = [...trailblazer.certifications, 'Salesforce CPQ Consultant'];
console.log(latestCertifications);
// Join Arrays as new array
const info = [...trailblazer.certifications,...myArray];
console.log(info);
// Iterables: arrays, strings, maps and sets
const myName = 'Srinu';
const chars = [...myName, ' ', 'Sfdc'];
console.log(chars);
// Supply array values as seperate arguments to a function
const newCertifications = [prompt('Enter Certification1'),prompt('Enter Certification2'),prompt('Enter Certification3')];
trailblazer.addCertifications(...newCertifications);
// Spread with object
const newtrailblazer = {...trailblazer,appExchange : 'NA'};
console.log(newtrailblazer);

Thursday, 15 July 2021

JavaScript Destructuring Object Salesforce

const trailblazer = {
name : 'Srinu',
address : {
state : 'Karnataka',
country : 'India'
},
certifications : ['Admin','PD I','PD II', 'Application Architect'],
trailhead : {
badges : 115,
points : 90725,
trails : 6
},
addCertification : function({month, year}) {
console.log(month,year);
}
}
// Destructuring Object
const { name, address, certifications} = trailblazer;
console.log(name, address, certifications);
// Destructuring Object by renaming the properties
const {name: personName, address: currentAddress, certifications: sfdcCertifications} = trailblazer;
console.log(personName, currentAddress, sfdcCertifications);
// Destructuring Object by assigning default value and renaming properties
const {
connections = {},
trailhead: myTrailhead = {}
} = trailblazer;
console.log(connections,myTrailhead);
// Mutating the variables
let num1 = 100, num2 = 200;
const obj = {num1: 10, num2: 20};
({num1, num2} = obj);
console.log(num1, num2);
// Nested objects
const {trailhead: {badges,points}} = trailblazer;
console.log(badges,points);
// Calling function with destructured input
const certification = {
month: 'July',
year: 2021
};
trailblazer.addCertification(certification);

JavaScript Destructuring Arrays for Salesforce

/*** Destructuring Arrays ***/
let myArray = [100,200,300];
let myArray2 = [500,[10,20]]
// Destructuring array into each variable
let [a,b,c] = myArray;
console.log(a, b, c); // 100 200 300
// Destructuring only required elements
const [x,,y] = myArray;
console.log(x,y); // 100 300
// Default Values while destructuring
const [p, q, r, s = 0] = myArray;
console.log(p, q, r, s); // 100 200 300 0
// Exchanging the variable values
[c, b, a] = [a, b, c];
console.log(a, b, c); // 300 200 100
// Destructuring the nested array
const [i,[j,k]] = myArray2;
console.log(i,j,k); // 500 10 20