SFDC Stop - Always the latest about Salesforce


Full Tutorial Series with videos, free apps, live sessions, salesforce consulting and much more.


Telegram logo   Join our Telegram Channel

Tuesday, 2 March 2021

Inheritance in JavaScript ES6 | Class Inheritance | JavaScript Tutorial Series by SFDC Stop

 Hello Trailblazers,


Welcome to the seventh tutorial in JavaScript Tutorial Series by SFDC Stop. In this tutorial, we're going to learn about Inheritance in JavaScript ES6. Inheritance is defined as the process where one (derived) class acquires the properties of another (base) class. We'll see how we can define a base class and a derived class, how we can call the constructor of the base class from the derived class, how we can use the base class methods from the derived class object with an example. This tutorial is published on SFDC Stop YouTube Channel. So, if you want to learn in detail, have a look at the tutorial video down below. Otherwise, you can scroll down to have a look at the code gist with explanation.

Tutorial Video


Concept

The concept of inheritance is to move from Generalization to Specialization. Inheritance plays a vital role in keeping your code reusable as you can keep all the methods that are common in a single base class and you can use them in derived (child) classes. You can basically create a hierarchy where each child has access to all the properties of it's parent as well as it has some other properties that are specific to itself.

Code Gist with Explanation

We're going to define a simple class named as Phone. This will be our base class. Then we're going to define another class named as TouchPhone which will be our derived class. Let's have a quick look at the code below and then we'll understand it properly:


Let's talk about the base class first. Our Phone class is accepting two parameters in it's constructor namely: name and price. The name and price received in the constructor is assigned to the data members of the class with the same name i.e. name and price. After the constructor() we have two methods that are responsible to print the name and price of the phone namely: printName() and printPrice()


Now, let's talk about the derived class. Our TouchPhone classs is extending the Phone class using the extends keyword, this class is our derived class. Inside the TouchPhone class, we have a constructor which is accepting 3 parameters namely: name, price and touchSensitivity. The name and price received in the constructor are passed to the constructor of the base class by using the super().


We know that the base class Phone accepts two parameters inside the constructor i.e. name and price, therefore, we've passed name and price in our super(). After that we've assigned the 3rd parameter which is nothing but touchSensitivity to the data member of the derived class with the same name. After the constructor, we have defined one method named as printTouchSensitivity() which is responsible to print the touch sensitivity of the touch phone.


Conceptual Note: There are some properties which are common to every mobile phone for ex: name and price. That's why we've kept them as a part of the base (parent) class. Now, there can be some phone specific properties as well. Like: we can divide a phone into 2 basic categories:


1. A touch screen phone


2. A basic phone with keypad


For this, we have derived a class from the phone class and named it as TouchPhone, which represents a touch screen phone with an additional property i.e. touchSensitivity. As we're moving from parent to child class, we're also moving from Generalization to Specialization as the child class has more specific properties as compared to base class.


On line number 39, we have created an instance of our TouchPhone class named as iPhone and passed the name, price and sensitivity as iPhone11, 200 and 1.5 respectively to the derived class constructor. The name and price are automatically passed to the Phone class constructor through the super(). Then we're calling the printName(), printPrice() and printTouchSensitivity() methods from the derived class object. The concept to learn here is that: The derived class object can directly access the methods of the base class and can also access the constructor of the base class using the super().


After that we just added a console.log('---------') to divide the result into two parts. In the second part, we're creating an instance of the base class named as basicPhone. We're passing two values inside the constructor named as: Basic Phone and 100. Then we're printing the name and price of the basic phone by calling the printName() and printPrice() methods.


The output when the above code is executed is given below:


As you can see above, we're able to get the name, price and touch sensitivity of the touch phone as: iPhone11, 200 and 1.5 from the instance of the TouchPhone class. After that we're displaying the name and price of the basic phone which is Basic Phone and 100 using the instance of Phone class.


So, we understood that the derived class can easily call the member functions of the base class but is the reverse possible? Can the base class call the member functions of the derived class? Let's try that..!!


As you can see below, we modified our code a little and at the last line we're trying to call the printTouchSensitivity() method of the derived class from the instance of the base class. 



The execution of the above code resulted in an error as "Uncaught TypeError: basicPhone.printTouchSensitivity is not a function". This is because, we cannot call the member function of a derived class from the base class.


To summarize, the learnings are given below:-

  • Inheritance is defined as the process where one (derived) class acquires the properties of another (base) class.

  • A class can extend another class by using extends keyword.

  • The derived class can call the constructor of the base class by using the super().

  • The instance of the derived class can directly call the methods of the base class.

  • The instance of the base classs cannot directly call the methods of the derived class.

That's all for this tutorial. I hope you liked it. All the code used in this tutorial is available on GitHub and you can have a look at that by clicking here. Make sure to have a look at the video if you want to learn in detail and let me know your feedback in the comments down below.

Happy Trailblazing..!!

Sunday, 21 February 2021

ES6 Classes in JavaScript | JavaScript Classes Private Variables | JavaScript Tutorial Series by SFDC Stop

Hello Trailblazers,


Welcome to the sixth tutorial in JavaScript Tutorial Series by SFDC Stop. In this tutorial, we're going to learn about ES6 classes in JavaScript. We'll see how we used to define classes in JavaScript before ES6 and how easy it is to define a class now using ES6 syntax. We'll also learn about defining private variables in JavaScript classes. This tutorial is published on SFDC Stop YouTube Channel. So, if you want to learn in detail, have a look at the tutorial video down below. Otherwise, you can scroll down to have a look at the code gist with explanation.

Tutorial Video


Code Gist with Explanation

How we used to create a class in JavaScript before ES6?

We're going to define a simple class named as Car. The code for the class is given below:


As you can see above, the class car is defined as a function itself because classses in JavaScript are special functions. It will receive two parameters inside the constructor: name and speed, which are parameters to the car function in the code. These two parameters name and speed are used to initialize two data members of the class with the same name i.e. name and speed. Note that the data members are referred by using this keyword.


After the constructor, we have a function named as showSpeed() which is used to display the speed of the car. This function belongs to the Car class, that is why we've used Car.prototype.<function-name> syntax to define the member function. This function can access the data members of the car by using the this keyword.


After the function definition, we simply created the instance of the car class named as audi and passed the name and speed of the car in the constructor as: audi and 200. Finally, we called our showSpeed() method to display the speed of the car by using the class instance. The output when we run this code is given below:

The code is executed successfully and we're getting the expected result i.e. 200 which is the speed of the car.

How can we now define a class in JavaScript using ES6 syntax?

Using ES6 we can define a class using class keyword and the constructor of the class can be defined using constructor keyword. Let's have a look at the same Car class but this time, it's defined using ES6 as shown below:

As you can see in the above code, this time we've defined a Car class using the class keyword. This syntax is very similar to other programming languages. Inside the class, we've defined a constructor by using the constructor keyword. This constructor is accepting two parameters: name and speed. The two data members name and speed of the class are referred using this keyword inside the constructor and are given the values passed inside the constructor. After that we've a function inside the class itself named as showSpeed() which is responsible to display the speed of the car.

The remaining code snippet is same, we've again created the instance of the Car class named as audi and passed the name and speed of the car in the constructor as: audi and 300. Finally, we called our showSpeed() method to display the speed of the car by using the class instance. The output when we run this code is given below:


As you can see above, we're getting the speed of the car displayed as 300 in the console.

Can we have private variables inside classes in JavaScript?

The answer is YES! You can define private variables inside classes in JavaScript. Let's have a look at the modified code snippet to understand how:

As you can see above, we have added one more parameter to the constructor of our class Car named as: color. This parameter is assigned to a new data member identified by #color which is also declared above in the class. Here # specifies that, the color data member is private. Also note that it's mandatory to declare the private data member in the class body, that's why we've declared it above at line number 3.

We've also created one more member function named as showColor() which is displaying the value of color data member. Below the class, we've added two statements at line number 22 and 23, where we're displaying the name and speed of the car audi by directly accessing the data members outside the class. We can do that because the data members are public and we can access the public data members directly outside the class. However, we also have a commented statement at line 24 where we're trying to access the color data member outside the class.

As we know, that the color data member is private, we cannot access it outside the class. You can give it a try by un-commenting the line and running the code snippet. You'll get an error as shown below:


If we comment that line again and try to access the color using the showColor() function which is called at the last, the code will work fine and you'll get the output as shown below:


So, as you can see above, we're getting the value 300 from showSpeed(), then we're getting the name and speed of the car by directly accessing the public variables outside the class with values: audi and 300. Finally, we're displaying the color of the car by using the showColor() which is displayed as red as it's the same color that we've passed in the constructor of the class.

To summarize, the learnings are given below:-
  • Before ES6, we used to define a class by using the syntax of a function because classes in JavaScript are Special Functions. The member functions of the class were defined outside the classs function.
  • ES6 made it very simple to define a class using the class keyword. We can define a constructor inside the class as well by using the constructor keyword. The member functions of the class can be defined inside the class body itself.
  • We can also define private variables in a class. Private variables must be explicitly declared inside the class body and are prefixed by a #. They can only be accessed inside class member functions.

That's all for this tutorial. I hope you liked it. All the code used in this tutorial is available on GitHub and you can have a look at that by clicking here. Make sure to have a look at the video if you want to learn in detail and let me know your feedback in the comments down below.

Happy Trailblazing..!!

Tuesday, 9 February 2021

ES6 Spread Operator | Rest Parameters in JavaScript | JavaScript Tutorial Series by SFDC Stop

 Hello Trailblazers,


Welcome to the fifth tutorial in JavaScript Tutorial Series by SFDC Stop. In this tutorial, we're going to learn about Spread Operator in ES6. We'll see how we can spread an array into multiple elements using the spread operator and also, how we can combine multiple elements into a single array by using spread operator as a rest parameter in ES6 JavaScript functions. This tutorial is published on SFDC Stop YouTube Channel. So, if you want to learn in detail, have a look at the tutorial video down below. Otherwise, you can scroll down to have a look at the code gist with explanation.

Tutorial Video


Code Gist with Explanation

How we used to pass array elements as parameters inside the function before ES6?

We're going to define a simple JavaScript function which will display the array elements passed as parameters. The code for that function is given below:


As you can see, we're having a function named as eats which has 3 parameters fruit1, fruit2, fruit3 and will print the statement consisting of the values of these. We're passing the fruits array elements into the function as fruits[0], fruits[1] and fruits[2]. The output when we run this code is given below:


The code is executed successfully and we're getting the expected result i.e. Baby eats:- apple, mango and banana

How can we now pass array elements into function using spread operator in ES6?

ES6 has defined spread operator and it made it much simpler to pass array elements as parameters to a function in JavaScript. The updated code is given below:

As you can see in the above code, we're passing the array elements to function parameters by using the statement eats(...fruits);. When we specify three dots (...) before an array then it spreads the array into it's elements. That's why this operator is known as the spread operator. Therefore, while passing the array into the eats function, we're spreading it into multiple elements. The output when the above code is executed is given below:


As you can see above, the output is exactly the same as we've seen before.

What are Rest parameters in JavaScript ES6?

We've seen above that the ES6 spread operator (...) can be used to break an array into it's elements. But do you know that we can also use it to combine multiple JavaScript variables into a single array? We can pass multiple parameters to a JavaScript function and we can combine all those parameters to an array by using the spread operator. Let's see how:

As you can see above, we have created a function named as car. It has two parameters: name and features with a spread operator. This features parameter is nothing but an array and we're displaying the features of the car by iterating this array using the forEach loop. You can see above that we've called the car method with different values as: car('Audi', 'Great Speed', 'Good Color', 'Comfort', 'Good Looks');. So, here, the first argument is the car name Audi and is assigned to the name parameter. All the other arguments are car features and are combined together to form the features array by using the spread operator.

This is why we say that the spread operator can also be used as a Rest Parameter because it collects all the extra - rest of the parameters that are passed to a JavaScript function and forms an array. The output of the above code is given below:


As you can see above, all the features of the car are combined in a features array and we're able to display those features.

Concatenating two arrays using Spread Operator

Do you know we can also concatenate two arrays using spread operator? Let's have a look at the below code snippet to understand how:

As you can see in the above code snippet, we've created two arrays: features and moreFeatures. The features array is having 4 entries :- 'Great Speed', 'Good Color', 'Comfort' and 'Good Looks', whereas the moreFeatures array is having 2 entries:- 'Great Mileage' and 'Amazing Design'. We're using Array.push() method on the features array as features.push() which is basically used to push one element at the end of the array but here, we're spreading our moreFeatures array into multiple elements by using the spread operator. Therefore, these elements are then pushed one by one into the features array automatically and both the arrays are combined into the features array.

The output we're getting when the above code snippet is executed is given below:


As you can see above, it's pushing the elements of moreFeatures array into the features array using the push() and we're getting the output as 6, as the total number of elements are now 6. Also, we displayed the features array and it's showing us all the 6 features together. Therefore, we're able to concatenate two arrays using the spread operator. 

The same can be achieved when you're defining the second array as shown in the below code snippet:

As you can see above, we've passed the features array as an array element after the 'Amazing Design' entry while defining the moreFeatures array. We're spreading this array using the spread operator. This means that the moreFeatures array should contain all the elements of the features array after it's own two elements. Let's have a look at the output below as we're displaying the moreFeatures array using console.log() :


As you can see above, the moreFeatures array has all the elements of the features array appended after it's own elements, so, the spread operator is working perfectly fine.

To summarize, the learnings are given below:-
  • Before ES6, if we need to pass array elements as parameters to js function, each array element was specified one by one using the index as array[0], array[1], array[2].
  • ES6 made it very simple and we can simply pass the whole array as a single parameter by using the spread operator like: ...array
  • In case, we're passing passing multiple values to a function we can combine them to an array using the spread operator. The spread operator is called a rest parameter in such a case.
  • We can also concatenate two arrays using the spread operator.

That's all for this tutorial. I hope you liked it. All the code used in this tutorial is available on GitHub and you can have a look at that by clicking here. Make sure to have a look at the video if you want to learn in detail and let me know your feedback in the comments down below.

Happy Trailblazing..!!

Tuesday, 2 February 2021

ES6 Default Parameters in JavaScript Functions | JavaScript Tutorial Series by SFDC Stop

Hello Trailblazers,


Welcome to the fourth tutorial in JavaScript Tutorial Series by SFDC Stop. In this tutorial, we're going to learn about ES6 Default Parameters in JavaScript Functions. We're going to see how we used to define default parameters before ES6 and how we can do it using ES6 syntax. This tutorial is published on SFDC Stop YouTube Channel. So, if you want to learn in detail, have a look at the tutorial video down below. Otherwise, you can scroll down to have a look at the code gist with explanation.

Tutorial Video


Code Gist with Explanation

We're going to define a simple JavaScript function which will add two values and display the result. The code for that function is given below:


Now, let's run this code once and then we'll learn about the default parameters. The output when we're calling this function with values 3 and 5 is given below:


As you can see, we're getting the result of addition of 3 and 5 displayed as 8. 

How we used to define default parameters before ES6?

Now, let's see how we used to define default parameters before ES6. For this, we're going to provide a default value for the parameter b. The updated code is given below:

As you can see in the above code, inside the function we're checking that if b is defined i.e. we're passing a value for parameter b, we're using that b itself otherwise, we're going to assign a default value to b which is 2. The output when the above function is called is given below. This time, we're only going to pass 1 value to the function which will be used for parameter a and the parameter b will take up the default value.


As you can see above, we're passing only one parameter as 3 and the default value 2 is being taken up for parameter b giving us the total sum as 5.

How can we define default parameters using ES6 syntax?

ES6 has made it much simpler to define default parameters for functions in JavaScript. We're going to re-write the same function again now and see how we can define a default value for parameter b using ES6. The updated code is given below:

As you can see above, it is so simple to provide the default value for any parameter in ES6 by just giving that value with an equals = sign. Here we're giving the default value for parameter b as 2 by specifying b=2 in the function parameters itself. The output when the above function is called is given below:


As you can see above, we're getting the output as 5 when the parameters a and b are added as the default value for b is automatically considered as 2 and we're passing the value for a as 3.

How can we define a default value if we're passing an object to a function in JavaScript?

The syntax to define the default value, when an object is passed to a function parameter is given below:

As you can see in the above code snippet, we've defined a function named as personAge which is accepting two parameters, the age of the person and the person object itself. The person object has two properties:- firstName and lastName. We've defined the default value for firstName as Richard and the lastName as Hendricks. Therefore, if this function is called with just one parameter, these values will be taken up as the default values for the person object.

One important thing to notice is that we're assigning an empty object to the person object which has the default values like:- { firstName = 'Richard', lastName = 'Hendricks' } = {}. This is important because we're telling the JavaScript function that the default value for this second parameter as a whole is an empty object which has no values for firstName and lastName, so, the default values for these properties i.e. Richard and Hendricks can be taken up.

The output we're getting when the above function is called is given below:


As you can see above, we've only passed a single value for the age parameter as 20 and we're getting the output as: Richard Hendricks is 20 years old which is perfect. So, this is how you can define default values for an object passed as a parameter to a JavaScript function.

To summarize, the learnings are given below:-
  • Before ES6, we were using conditional operator to define the default values for parameters
  • ES6 made it very simple and we can simply define a default value for a parameter by providing the value after the = sign at the same place where the parameter is defined
  • In case, we're passing an object to the function, we need to define a default value as an empty object after the = sign for the object parameter as a whole. Although, for the object properties, we can define the default values within the parameter definition. Both these steps are important to make sure that the object is initialized as well as the parameters also get their default values.

That's all for this tutorial. I hope you liked it. All the code used in this tutorial is available on GitHub and you can have a look at that by clicking here. Make sure to have a look at the video if you want to learn in detail and let me know your feedback in the comments down below.

Happy Trailblazing..!!

Thursday, 28 January 2021

SOQL FIELDS() is now Generally Available | Advantages and Limitations | Salesforce Spring '21 Release | SFDC Stop

Hello Trailblazers,


In this post, I am going to discuss about one of my favorite updates from Salesforce Spring '21 Release (v51.0) for Salesforce Developers which is:

SOQL FIELDS() is Generally Available

This is the best thing I read in this release, no more long SOQL queries to retrieve a lot of fields while integrating with external systems. 

You must be thinking that we don't need to update the apex code again and again to accomodate more fields due to frequent changes in the data model. IS IT REALLY SO? Let's find out.

Concept

You can query standard fields by using FIELDS(STANDARD) in the SOQL query:

SELECT FIELDS(Standard) FROM Account


Although most of the fields I queried are NULL :P because I just created some dummy account records using apex, but this is really amazing!!

You can query custom fields by using FIELDS(CUSTOM) in the SOQL query, Make sure to specify a limit as well (at max 200) as shown below:

SELECT FIELDS(Custom) FROM Account ORDER By LastModifiedDate DESC LIMIT 2



You can query all fields standard + custom by using FIELDS(ALL) in SOQL query:

SELECT FIELDS(ALL) FROM Account ORDER BY LastModifiedDate DESC LIMIT 5


As you can see above, first of all we're getting all the standard fields and at the end we're getting al the custom fields as well.

What CAN be done and what NOT?

1. You cannot have duplicate fields in SOQL query. Have a look at the below query, I am using FIELDS(Custom) which will query all custom fields and I am explicitly specifying Cost__c custom field as well which results in field duplication.


2. You cannot query custom fields using Apex. For Ex: the below code is not valid.


I even tried the above function by using Database.query() the file was saved successfully but I wasn't able to execute the function and got the same error as you can see below:


Although you can query all standard fields with some custom fields explicitly specified as shown below:


It worked perfectly fine as you can see the result:


You'll find the similar behaviour, if you try to use FIELDS(ALL).

Reason: FIELDS(ALL) and FIELDS(CUSTOM) are considered unbounded because the number of fields are not predetermined because the custom fields are created by admins/developers. Learn more about bounded and unbounded limitations here.

3. You must specify a LIMIT while querying unbounded fields i.e. using FIELDS(ALL) or FIELDS(CUSTOM) in the query. The limit can be 200 at max.


4. If you're specifying a set of IDs in the query, that must be a set of 200 ids at most. For ex:


5.  The SOQL query may query less records than specified in the LIMIT while using FIELDS() if your object contains CLOB or BLOB fields. In this case, it's recommended to checkout the number of records returned and update your offset accordingly to get the next set of records. You can use nextRecordsUrl  in case of REST API and queryMore() in case of SOAP API to query more records.

6. If you try to query custom fields for an object that doesn't have any, you'll receive an error as shown below:


Although if you specify even a single standard  field along with this query, the error will be ignored and your query will return the standard fields as shown below:


7. If you don't have access to a field (Field Level Security) it's automatically ignored. If you see in point number 4, the field Cost__c was also queried. However, now, I have removed the access to that field. You can see the result below:


So, that's all for this post everyone, I hope you liked it. I am also hoping that we can get over this bounded and unbounded fields limitation in the future releases so that we can query all custom fields in apex as well. Let me know your feedback about this post and your suggestions in the comments down below. 

Happy Trailblazing..!!

Tuesday, 26 January 2021

ES6 Fat Arrow Functions in JavaScript | JavaScript Tutorial Series by SFDC Stop

 Hello Trailblazers,


Welcome to the third tutorial in JavaScript Tutorial Series by SFDC Stop. In this tutorial, we're going to learn about ES6 Fat Arrow Functions in JavaScript. We're going to start from the beginning and see how we can define a function in JavaScript and finally we'll reduce that function to a single line of code using Fat Arrow sytnax. This tutorial is published on SFDC Stop YouTube Channel. So, if you want to learn in detail, have a look at the tutorial video down below. Otherwise, you can scroll down to have a look at the code gist with explanation.

Tutorial Video


Code Gist with Explanation

Q. Write a function to calculate the perimeter of a circle in JavaScript?

The basic syntax to define a function in JavaScript is given below where we're defining a function to calculate the perimeter of a circle.


As you can see in the above code, we have defined a function which is taking radius of a circle as a perimeter. Inside this function, we've a constant named as PI with value 3.14 and finally we're returning the perimeter of a circle which is nothing but 2 * PI * radius. Upon running the above code snippet which is calling the function with the value of radius as 10, the output we're getting is shown below:

As you can see above, we're getting the perimeter of the circle with radius 10 as 62.8. This is how you can Define a Simple Function in JavaScript. Now, let's update this code and this time we're going to assign a function to a variable and call a function afterwards. This is nothing but Another way of defining a function in JavaScript, as given below:


Here we're defining a function using the function keyword but instead of providing a name for the function after the function keyword, we're assigning that function to a variable with name perimeterOfACircle2 and using that variable to call this function in console.log statement. The output we're getting is shown below:



As you can see, we're getting the same output here as well i.e. the perimeter of a circle with radius 10 as 62.8. This is just another way of defining and using a function where we're assigning a function to a variable and using it.

Why do we need to use the function keyword again and again? Is there any alternative?

The answer is YES!. You can use the Fat Arrow => symbol instead of the function keyword to define a function. Have a look at the below code snippet:

Here we've replaced function(radius) with (radius) => i.e. we're using the fat arrow symbol to point to the function body after the parameters are defined within paranthesis. According to this syntax, we keep the parameters before the fat arrow => and the body of the function after the fat arrow. The output we're getting when the above code is executed is given below:


As you can see above, the output is still the same. We've reduced the characters in our function code a little using the fat arrow syntax. Now, the question is:

CAN WE REDUCE THIS FUNCTION TO A SINGLE LINE WITH FAT ARROW SYNTAX?

The answer to this question is, YES! You can. Let's have a look at the updated code snippet below, where we've reduced this function code to a single line:

When you try to execute this code snippet, you'll get the output as shown below:


As you can see above, our output is still the same but we've reduced our JavaScript function to a single line using ES6 fat arrow syntax. Here are few things to notice in this code snippet:

  1. Following the ES6 syntax we have to keep the parameters to the left hand side and the function body to the right hand side of the fat arrow =>

  2. While reducing the function to a single line, you need to have the return value of the function to the right hand side of the fat arrow. Notice that here we've removed the constant PI but instead used the value 3.14 directly in the calculation followed by the fat arrow which will be returned. Also, we don't need to specify the return keyword here.

  3. If you only have a single parameter passed inside your function, you don't need to cover it by paranthesis () you can simply keep it as is. You can see we've removed the paranthesis from the radius here.

  4. Basically, we're reducing the function body to a single line which is being returned and specifying that line after the fat arrow.

Isn't it amazing..!! You can reduce your JS function to a single line using ES6 fat arrow syntax. Let's see an example function with multiple parameters as well. Have a look at the code below. This time we're going to calculate the perimeter of a rectangle by passing in two parameters length and breadth:


As you can see above, we've directly defined this function using ES6 syntax. this function is taking two parameters length, breadth and is returning the parameter of a rectangle which is nothing but 2 * (length + breadth).

The output of the function is given below:


As you can see above, after passing the length as 10 and breadth as 20 we're getting the parameter as 60 which is correct 2*(10+20). Here, we have multiple parameters therefore, covering them by paranthesis () is important to keep your code syntactically correct.

To summarize, the learnings are given below:-
  • We can initialize a function by using the function keyword or by using the fat arrow =>
  • While using a fat arrow, we need to keep the parameters to the left side of the fat arrow symbol => and the function body to the right side of the fat arrow symbol.
  • If we can reduce the function body to one line, we can define it in a single line using fat arrow syntax by just keeping the return value after the fat arrow. In this case the return keyword is not mentioned.
  • If we have a single parameter, we can remove the paranthesis () as well but we do need to specify the paranthesis otherwise.

That's all for this tutorial. I hope you liked it. All the code used in this tutorial is available on GitHub and you can have a look at that by clicking here. Make sure to have a look at the video if you want to learn in detail and let me know your feedback in the comments down below.

Happy Trailblazing..!!

Tuesday, 19 January 2021

Everything about Constants in JavaScript | ES6 | JavaScript Tutorial Series by SFDC Stop

Hello Trailblazers,


Welcome to the second tutorial in JavaScript Tutorial Series by SFDC Stop. In this tutorial, we're going to learn about constants in JavaScript. This tutorial is published on SFDC Stop YouTube Channel. So, if you want to learn in detail, have a look at the tutorial video down below. Otherwise, you can scroll down to have a look at the code gist with explanation.

Tutorial Video


Code Gist with Explanation

Let's have a look at the code snippet given below in which we're defining a constant named as MONUMENT with the value "Taj Mahal":


What do you think will be the output of above code snippet? When you try to execute this code, you'll get the output as shown below:



As you can see that the value Taj Mahal is displayed properly. This means that We can provide a value to a constant while defining it.


Now, let's break this constant definition into two statements as shown below:


What do you think will be the output of above code snippet this time? When you try to execute this code, you'll get the output as shown below:





As you can see, we're getting an error as: Uncaught SyntaxError: Missing initializer in const declaration. This means that We must INITIALIZE a constant while defining it

Now, let's update this code snippet again and this time we'll initialize the MONUMENT constant and update it's value later on. The updated code snippet is given below:

What do you think the output will be when we execute the above code? When you try to execute this code, you'll get the output as shown below:


As you can see above, first of all, the value of the constant MONUMENT which was given during definition is displayed i.e. "Taj Mahal" but when we're trying to update the value of a constant we're getting an error as: Uncaught TypeError: Assignment to constant variable at <anonymous>:4:10. This means that We cannot assign a new value to a constant.

Now, let's consider one more scenario, this time, we're going to assign an object to a constant named USER. The code snippet for the same is given below:

When you try to execute this code snippet, you'll get the output as shown below:


As you can see above, the object which is assigned to our constant  USER is displayed properly. This object has two properties firstName and lastName. Now, let's update our code snippet and try to assign a new value to our USER constant. The updated code snippet is given below:


What will you think will happen now? The output of this code snippet is given below:


As you can see above, first of all our USER constant is displayed through first console.log statement with value of firstName as Rahul and lastName as Malhotra. After that we're getting an error which is similar to the error we saw previously i.e. Uncaught TypeError: Assignment to constant variable at <anonymous>:9:6

This means that even if you have provided an object to a constant you cannot update the constant as a whole. Now, one more question arises which is:

CAN WE UPDATE THE PROPERTY OF AN OBJECT ASSIGNED TO CONSTANT?

Let's find out. We've updated our code snippet again as shown below:


As you can see above, this time, we're not assigning a new value to our constant but we're updating the firstName to Richard and lastName to Hendricks. What do you think will happen now? Will JavaScript allow us to update the property of a constant or not? Let's see the output below:


As you can see, we haven't got any error. In the first console.log, an object is displayed with firstName as Rahul and the lastName as Malhotra and after updation, in the second console.log another object is displayed where the firstName is updated to Richard and the lastName is updated to Hendricks. Therefore, we got to know that If a constant is an object, we cannot assign a new value to that constant but we can update the properties of that constant.

To summarize, the learnings are given below:-
  • We must initialize a constant while defining it
  • We cannot assign a new value to a constant
  • If the constant is an object, we can update the property of that constant

That's all for this tutorial. I hope you liked it. All the code used in this tutorial is available on GitHub and you can have a look at that by clicking here. Make sure to have a look at the video if you want to learn in detail and let me know your feedback in the comments down below.

Happy Trailblazing..!!

Tuesday, 12 January 2021

Difference between let and var in JavaScript | let v/s var | ES6 | JavaScript Tutorial Series by SFDC Stop

 Hello Trailblazers,


Welcome to the first tutorial in JavaScript Tutorial Series by SFDC Stop. In this tutorial, we're going to learn about the difference between let and var in JavaScript. This tutorial is published on SFDC Stop YouTube Channel. So, if you want to learn in detail, have a look at the tutorial video down below. Otherwise, you can scroll down to have a look at the code gist with explanation.

Tutorial Video


Code Gist with Explanation

Let's have a look at the code snippet given below:


What do you think will be the output of above code snippet? Think about it. When you try to execute this code, you'll get the output as shown below:






As you can see that the value is updated only inside the function, this means that the var keyword supports function scope as the value is updated only inside the function and the variable which is declared outside the function remains unchanged.


Now, let's replace this var keyword with let and check the output again. Below is our updated code:


What do you think will be the output of above code snippet this time? When you try to execute this code, you'll get the output as shown below:





As you can see , the output is the same when you're replacing var with let. This means that Both the let and var keyword supports function scope. Now you must be wondering that:

 WHY SHOULD I USE LET INSTEAD OF VAR WHEN BOTH ARE SAME?

To answer this question, we need to study another code snippet. This time, we're going to replace the function with a block. Let's have a look at the code snippet given below:

What do you think the output will be when we execute the above code? When you try to execute this code, you'll get the output as shown below:






As you can see above, this time the value of the global variable is also updated even if we're assigning the value to a local variable inside an if block. This means that the var keyword doesn't support block scope. Let's try to replace this var keyword with let and check the output again. The updated code snippet is given below:

What do you think will be the output of the above code? When you try to execute this code snippet, you'll get the output as shown below:






As you can see above, this time the result is correct i.e. the value of the global variable is not updated inside the if block. This leads us to the conclusion that the let keyword supports block scope

To summarize, the learnings are given below:-

  • Both var and let keyword supports function scope.
  • var keyword doesn't support block scope
  • let keyword supports block scope

This was the reason when let was introduced, it was said that let is the new var because is supports block scope which makes JavaScript more similar as different programming languages and it leads to less errors.

So, next time when you're about to declare a variable in your JavaScipt code, make sure to use let instead of var.

That's all for this tutorial. I hope you liked it. All the code used in this tutorial is available on GitHub and you can have a look at that by clicking here. Make sure to have a look at the video if you want to learn in detail and let me know your feedback in the comments down below.

Happy Trailblazing..!!

Tuesday, 29 December 2020

Salesforce LWC Tutorial Part 7 | Wrapping up ToDo App Project | Add Spinner | Deploy to Salesforce

 Hello Trailblazers,

Welcome to the seventh and final tutorial in LWC Tutorial Series where we're building a ToDo App Project. We're focusing on the concept of Learning By Doing in this tutorial series. In this tutorial, we're going to refine our ToDo List component by adding a spinner and some validations in LWC. We're also going to deploy our todo list component to a Salesforce Org.


So, let's continue building the above application. This tutorial is published on SFDC Stop YouTube Channel. So, if you want to learn in detail, have a look at the tutorial video down below. Otherwise, you can scroll down to have a look at the code gist with explanation.

Tutorial Video


Code Gist with Explanation

I highly recommend you to have a look at the video to understand in detail. However, let's have a quick look at the code below to understand in short:-

Apex Class (ToDoListController.cls)

As you can see above, we haven't made any change in the apex class, so the code is same as it was in the previous tutorial.

JS Snippet (todo.js)

If you see carefully, we've defined a new variable named as processing which is initially true. This variable will be used to show a spinner whenever a call to apex is performed from our lwc component. Initially, it's true because we're loading the list of tasks from Salesforce when the component is initialized. We'll now see how we need to toggle this boolean attribute in js to show/hide the spinner at multiple places and finally, we'll add a spinner component to our HTML.

If you check the addTaskToList() we have added a check first of all i.e. if our this.newTask which is our task name is blank, the method will simply return and no operation will be performed, this check will stop the user to add a blank record in our todo list. After this, we've set the processing variable to true.We've done this at the beginning, because our apex call will be asynchronous and we want our spinner to display from the moment we click on the Add button until the task is inserted in Salesforce. 

Then, we've called out insertTask method which is responsible to insert a new task in Salesforce and we've linked a finally() method as well, after the then and catch method. Inside the finally method, we again set the processing variable to false. We've done this in the finally method because we want to hide the spinner irrespective of the fact that the call to apex is successful or not, so, it doesn't matter whether we're getting a successful response or an error from apex callout, the spinner will hide as the apex call is complete.

Remember setting up the id of the new task in our insertTask method as:- this.todoTasks[this.todoTasks.length - 1].id + 1 to prevent duplicacy? I have mentioned this in the previous blog because this was important although the detailed explanation of the same is given in the video embedded above as it's also a part of enhancement.

Now, let's move on to our deleteTaskFromList(), inside this method as well, you can see that we've set the processing variable to true before we're going to perform any operation to delete the particular task, this is because we want to show the spinner before executing any code. Then, we are finding the record id of the task to delete from salesforce and finally, we're calling the deleteTask method which is used to delete the task from Salesforce by using the record id. This method is also having a finally() method attached to it after the then and catch, where we've set the processing variable to false. The reason is same, we have to hide the spinner after the apex call is complete irrespective of the fact whether the task was deleted successfully or not.

Let's have a look at getTodoTasks() method now, as you know that this is a wire method, so, it'll be called automatically when the component is initialized. Remember, we kept the initial value of processing variable as true when we initialized it? We're going to make it false now when our wire method apex call is complete. As you can see, inside our getTodoTasks() method, we're setting processing to false when the response is received from salesforce irrespective of the fact that we're getting the data or error from salesforce side when we're loading the list of tasks.

Finally, in the refreshTodoList() method, initially, we have set the processing variable to true. I have linked a finally() method to the refreshApex method as well. Inside this finally method, we've set the processing variable to false as we did in other places.

HTML Snippet (todo.html)

If you see above, inside the first lightning-layout-item tag, we've added a template with a condition which specifies, if the processing variable is true, the lightning-spinner component will be visible which is kept inside this template tag. This lightning-spinner component is responsible to display the loading spinner and is controlled by the processing variable. We've already toggled the processing variable at various places in our js code in order to show/hide the loading spinner. If you see the lightning-input tag, we've have added another property there named as autocomplete, whose value is off. This property will stop the suggestions that are coming when we're typing the name of a new task. This is also an enhancement that you can add-on to your custom lwc components.

XML Snippet (todo.js-meta.xml)

Now, it's time to deploy our lwc component to Salesforce Org. As you can see in the meta file above, we've marked isExposed property as true which will make the component visible in Salesforce Org. Apart from this, we've added a masterLabel using which you can search this component in the page builder. A friendly description of the component is added as well and under the targets tag, we've added 3 target tags:-

lightning__RecordPage:- To make our component available to a record detail page.
lightning__AppPage:- To make our component available to an app page.
lightning__HomePage:- To make our component available to a home page.

Now you can deploy this component to a Salesforce org using VSCode and you can embed your component to the homepage and test it out.

That's all for this tutorial. I hope you liked it. All the code used in this tutorial is available on GitHub and you can have a look at that by clicking here. Make sure to have a look at the video if you want to learn in detail and let me know your feedback in the comments down below.

Happy Trailblazing..!!

Wednesday, 23 December 2020

Salesforce LWC Tutorial Part 6 | ToDo App Project | Call Apex Imperatively from LWC

Hello Trailblazers,

Welcome to the sixth tutorial in LWC Tutorial Series where we're building a ToDo App Project. We're focusing on the concept of Learning By Doing in this tutorial series. In this tutorial, we're going to learn how we can send the data to the apex controller from our ToDo List component by performing an imperative call to apex from LWC. We're going to use this while inserting a new task and deleting a task as we need to insert/delete the task record from Salesforce, when the button is clicked in our component.


So, let's continue building the above application. This tutorial is published on SFDC Stop YouTube Channel. So, if you want to learn in detail, have a look at the tutorial video down below. Otherwise, you can scroll down to have a look at the code gist with explanation.

Tutorial Video


Code Gist with Explanation

I highly recommend you to have a look at the video to understand in detail. However, let's have a quick look at the code below to understand in short:-

Apex Class (ToDoListController.cls)

As you can see above, we have created two more methods insertTask and deleteTask

insertTask() is used to insert a new task with the subject which will be passed in this apex method as a parameter. This subject will be nothing but our todo task name that we've added to the todo list. OwnerId of the new task will be the id of logged in user, status is hardcoded as "Not Started" and the priority is "Normal". The new task which is inserted is returned from the method.

deleteTask() is used to delete a task from salesforce. It accepts the record id of the task to be deleted as a parameter and it deletes that task. It returns true, if the task is successfully deleted. Otherwise, returns false.

JS Snippet (todo.js)

Let's have a look at the import statements first of all, we have imported the insertTask and deleteTask method from my ToDoListController. 

Now, inside our addTaskToList() we have called insertTask method where we passed the name of our todo task which is stored in this.newTask variable, in the subject parameter. We have console logged the result of that apex call to debug what's coming in the response, this result will be the new task record which is inserted in Salesforce. Once the task is inserted, we're going to push this task in this.todoTasks list where id of the new task is calculated based on the number of tasks that are present in the list. If the number of tasks are more than 0, we'll take the id of the last task in the list, add 1 to it to get the id of the new task which is now added to the todoTasks list. Otherwise, the id of the new task is 0 if the todoTasks list is empty. This is important to make sure that we don't have tasks with duplicate ids in the list ( have a look at the video which will be provided in the next blog (part 7) to see the issue with duplicate ids in detail ). The name of the new task as we know is the value of this.newTask variable. We have added one more property to our new task here which is the recordId of the task. This property will store the salesforce record id of the newly inserted task which we can access using result.Id. As earlier, we can make the value of this.newTask as empty after the task is inserted. We've also added a catch to console log the error (if any) and we also have a finally block to assign the processing variable to false which is a small enhancement and we'll learn about it in the next tutorial.

Finally, inside our deleteTaskFromList() we have created one more variable which is named as recordIdToDelete. This variable will be used to delete the task from salesforce by using the salesforce record id. After the for loop, we've populated the recordIdToDelete variable by the recordId property of the todo task which is present at todoTaskIndex in the todoTasks list. Now, as we have the salesforce record id, we've called our deleteTask method in which we have passed the recordIdToDelete to the recordId parameter. As we know, this method will delete the task from salesforce and will return true if the task is successfully deleted, otherwise it'll return false. Therefore, we'll have a boolean value in the result variable. If the result is true, we'll remove the task present at todoTaskIndex from the todoTaks list. Otherwise, we'll simply console log the message i.e. Unable to delete task. We've also added a catch to console log the error (if any) and we also have a finally block to assign the processing variable to false which is a small enhancement and we'll learn about it in the next tutorial.

HTML Snippet (todo.html)

We've added some enhancements in the html file about which we'll learn in the next tutorial. Stay tuned..!!

That's all for this tutorial. I hope you liked it. All the code used in this tutorial is available on GitHub and you can have a look at that by clicking here. Make sure to have a look at the video if you want to learn in detail and let me know your feedback in the comments down below.

Happy Trailblazing..!!

Wednesday, 23 September 2020

Salesforce LWC Tutorial Part 5 | ToDo App Project | Wire Service linked to Function and RefreshApex

 Hello Trailblazers,

Welcome to the fifth tutorial in LWC Tutorial Series where we're building a ToDo App Project. We're focusing on the concept of Learning By Doing in this tutorial series. In this tutorial, we're going to learn how we can fetch the data from the apex controller for our ToDo List component using wire service in LWC. We're going to bind our wire service to a function in js which will receive the response. This time we'll be able to mutate the ToDoList as it won''t be directly binded with wire service. We'll also learn about RefreshApex function which will be used to refresh the browser cache.


So, let's continue building the above application. This tutorial is published on SFDC Stop YouTube Channel. So, if you want to learn in detail, have a look at the tutorial video down below. Otherwise, you can scroll down to have a look at the code gist with explanation.

Tutorial Video


Code Gist with Explanation

I highly recommend you to have a look at the video to understand in detail. However, let's have a quick look at the code below to understand in short:-

Apex Class (ToDoListController.cls)

As you can see above, I have created two more methods insertTask and deleteTask

insertTask() is used to insert a new task with the subject which will be passed in this apex method as a parameter. This subject will be nothing but our todo task name that we've added to the todo list. OwnerId of the new task will be the id of logged in user, status is hardcoded as "Not Started" and the priority is "Normal". The task inserted is returned from the method.

deleteTask() is used to delete a task from salesforce. It accepts the record id of the task to be deleted as a parameter and delete that task. It returns true if the task is succesfully deleted. Otherwise, returns false.

JS Snippet (todo.js)

Let's have a look at the wire method first which is the second last method in the above code. It's calling the same getTasks method which is imported from the apex controller like we did in the previous tutorial, the only difference here is that, instead of binding a variable, we've binded a function with the wire method. The response object in this case (which is having data and error as properties) is not directly assigned to a variable but it's coming as a parameter named response in the getTodoTasks() method which is binded with wire service. This response is stored in the todoTasksResponse variable which we've defined in the beginning of the class. After that we've stored the data and error from the response object into data and error variables for simplifying code.

If we have the data received successfully, we're re-initializing the todoTasks variable to empty array and pushing all the tasks one by one by using the foreach loop on the data array. The id of each todo task will be the (total array length + 1) (to keep it unique), the name of each todo task will be the Subject of the task received from salesforce and the recordId of each todo task will be the id of the task received from Salesforce. We're storing recordId here as well as it'll help us to delete the todoTask from salesforce in our next tutorial.

In case of an error we're displaying that in the console.

We've added a refreshTodoList() method as well which will be used to refresh the todo list from server on clicking the refresh/sync button. This method is calling the refreshApex() imported from @salesforce/apex which is used to refresh the response of wire method stored in browser cache. We're passing todoTasksResponse in this method which is nothing but the response received in our wire method.

I've also reset the addTaskToList() from Tutorial 3 as discussed in the previous tutorial that we don't be retaining/using any code of Tutorial 4 in further tutorials.

Note:- Try to add a new task to your todo list. You'll notice that this time you'll be able to mutate/update the todo list as we haven't directly binded the todoTasks array to wire service. Instead we've received the tasks list (response) in the function as a parameter and updated the todoTasks array manually.

HTML Snippet (todo.html)

We've reset the HTML code also from Tutorial 3 and have done some important changes. If you see the refresh button (lightning-button-icon) in the beginning of lightning:card, you'll notice that it's has an onclick attribute with the value as:- refreshTodoList as it'll call this method from js whenever the button is clicked to refresh the todo list. I have also updated the alternative-text and title from Sync to Refresh.

Rest all the code is same as it was in Tutorial 3. We've done the main effort in js to link wire service with a function and we've also used refreshapex which will be called when the refresh button is clicked.

Give it a try and let me know your observations in the comments down below.

Important Observation:- If you see carefully while testing, you'll notice that the refreshApex() is only refreshing the todo list, when there is a change on the server side (Try inserting a new task record directly in salesforce and click on the refresh button 2-3 times in your todo list to check how many times the wire service is refreshed). Basically, the refreshApex() only update the browser cache when there is a change on the server side otherwise it won't do anything. So, your apex calls are preserved. Thanks to LWC...!!

That's all for this tutorial. I hope you liked it. All the code used in this tutorial is available on GitHub and you can have a look at that by clicking here. Make sure to have a look at the video if you want to learn in detail and let me know your feedback in the comments down below.

Happy Trailblazing..!!

Monday, 14 September 2020

Salesforce LWC Tutorial Part 4 | ToDo App Project | Understanding Wire Service Immutability

Hello Trailblazers,

Welcome to the fourth tutorial in LWC Tutorial Series where we're building a ToDo App Project. We're focusing on the concept of Learning By Doing in this tutorial series. In this tutorial, we're going to learn how we can fetch the data from the apex controller for our ToDo List component using wire service in LWC. We'll learn about how we can bind our return value to a property by using wire and we'll try to mutate/change that property and thereby learn about the immutability property of wire service.

Note:- We'll not be using the changes that we'll do in this tutorial as a base in further LWC tutorials for ToDo App Series. This tutorial is important because, It's Equally important to understand WHAT NOT TO DO as it is to understand WHAT TO DO. We'll be learning about immutability property of wire service in this tutorial and we'll see how we can fetch the data from apex to lwc component using wire service.


So, let's continue building the above application. This tutorial is published on SFDC Stop YouTube Channel. So, if you want to learn in detail, have a look at the tutorial video down below. Otherwise, you can scroll down to have a look at the code gist with explanation.

Tutorial Video


Code Gist with Explanation

I highly recommend you to have a look at the video to understand in detail. However, let's have a quick look at the code below to understand in short:-

Apex Class (ToDoListController.cls)

As you can see above, I have created a simple method named as:- getTasks() which will return the list of tasks assigned to the logged-in user. Notice that I have added:- @AuraEnabled(cacheable=true) annotation to the method as it's required in order to make it available to the wire service. Let's have a look at the JavaScript code now.

JS Snippet (todo.js)

As you can see above, I have imported the getTasks method from the apex controller and wire service from lwc. At the end of the js, I have called getTasks method using the wire service and binded the response with todoTasks variable. It's the same variable that we initialized to an empty array in the previous tutorials (I've commented that code as you can see above the newTask variable declaration). Now, this todoTasks variable will store the response that we're getting by calling getTasks method i.e. an object with 2 keys:- data - which will contain the list of tasks and error - which will contain the error messages as you can see in the comments below the wire service.

Also, in the addTaskToList() method, I've commented the previous code of pushing the new task to todoTasks list as now we'll be pushing the new task to todoTasks.data as the list of todoTasks is present there. The id and name keys of each task are now replaced by Id and Subject as we're getting those tasks from apex now. For a new ToDo Task, the Id will have a value:- this.todoTasks.data.length + 1 instead of this.todoTasks.length + 1 as the list of todo tasks is now stored in this.todoTasks.data.

HTML Snippet (todo.html)

If you notice carefully, I have updated the todoTasks array in the for:each loop. Instead of todoTasks, I am using todoTasks.data and instead of using todoTask.idtodoTask.name, I am using todoTask.Id and todoTask.Subject

I have also wrapped this for:each loop under an if condition using <template if:true={todoTasks.data} which will check, if the data under the todoTasks object is defined or in simple words we can say that it'll check, if the tasks are fetched from the server successfully, as it may take some time to fetch the data from the server when the component is rendered. Once all the data is fetched, it'll go inside this template with if condition and render all the todo tasks using a for:each loop.

In the output you'll see that the todoTasks are fetched from salesforce successfully and you'll be able to view those. However, if you try to add a new todoTask to the list, you won't be able to do that as All the data which is fetched by using the wire service is Immutable (can't be updated). We'll see the solution to this issue in the next tutorial, where we'll bind a function with the wire service instead of a variable.

That's all for this tutorial. I hope you liked it. All the code used in this tutorial is available on GitHub and you can have a look at that by clicking here. Make sure to have a look at the video if you want to learn in detail and let me know your feedback in the comments down below.

Happy Trailblazing..!!