Friday, January 6, 2023

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);

No comments:

Post a Comment

Understanding Wire vs Imperative Apex Method Calls in Salesforce Lightning Web Components (LWC)

Understanding Wire vs Imperative Apex Method Calls in Salesforce Lightning Web Components (LWC) Introduction: Salesforce Lightning Web ...