Javascript Standards For Salesforce Lightning Web Component (LWC)

javascript standards for salesforce lightning web components (LWC)

JAVASCRIPT STANDARDS FOR LWC

In the previous Episode, we already discussed some basics concepts of the Lightning Web Components but this episode will give you a clear idea of all the syntax issues and new concepts.

As we know whenever we are running/loading any lightning component or LWC component on the browser it follows some web standards.

Wherever these standards also impact on our developing languages, Hence we need to update our coding standards so that our lightning web components are compatible with the latest web browser.

When we are talking about salesforce lightning web component, It follows the following web standards :

Web Standards For LWC :
  • Web Components
  • Templates
  • Custom Elements
  • Shadow DOM
  • Metadata
  • ECMAScript 7
  • Events
  • Standard Elements
  • Rendering 

ECMAScript LWC Compatibility : 
It's a language standard for developing lightning web components, It uses ECMAScript 6 and above. This language currently supports all the latest web browser like Apple Safari, Google Chrome, Microsoft Edge.

Now, Let's talk about the important javascript standards and changes you need to before starting with Lightning Web Components.

1. Decorators
2. DispatchEvent and CustomEvent
3. QuerySelectors
4. Import/Export
5. Spread Notation
6. Slots
7. Promises
8. String Interpolation + Let/Const

Let's discuss all these standards one by one....Get....Set...Go...Kid ⚡️

1. Decorators :
Decorators tell the compiler that specific thing you need to do with the code. Just like in Aura components we use @AuraEnabled in apex code. These decorators are also called as a magic placeholder.
Decorators we can use for LWC components are :

@track :
  • As this helps you to communicate inside your components (no communication of values from this component), Hence this is called private reactive property.
  • The @track tells to your compiler that you need to watch between backend code and frontend activity. For Example: whenever there are changes made you need to update the front end and then you need to update that frontend variable.
  • Let's consider a simple example, When I am adding two numbers as variable a + b and result at c. As soon as I update or change the input of a and b we need to perform the calculation in the backend and update the frontend result in c.
@api : 
  • It Means whenever you are developing a code its a private by default and if you want to make it public so that other things and call and reach into it, You can put @api decorator. Hence it's called public reactive property.
@wire :
  • It is a reactive service for data.
  • It is used to connect functions and variables to data.

These decorators are very important while implementing salesforce lightning web components.

2. DispatchEvent and CustomEvent :
- These DispatchEvent are also part of web standards.
- These events can be raised from Child to Parent.
- Very important about these events it the event will be preceded by putting Name of the event with 'on', Hence it is recommended not to write 'on' along with your event name because you are already using onchange keyword inside your markups as onchange handler.

SYNTAX :

childCmp.js
-----------------------------------------------------
const changeEvent = new CustomEvent('change', {detail: this.roles});
this.dispatchEvent(changeEvent);
-----------------------------------------------------

parentCmp.html
-----------------------------------------------------
<c-role-filter onchange={handleRoleChange}>
</c-role-filter
-----------------------------------------------------

as you can see the onchange handles the change event in the top childCmp components. Of course for passing the values between these components we will also in @api decorators in our code.

3. QuerySelector :
As we have already worked with client-side javascript in lightning components, where we used Document.getElementById, But sorry It will not work for you in LWC due to security issues.

Hence instead of Document.getElementById as per new web standards, they introduced QuerySelector for LWC.

Let's consider an example :

card.html
---------------------------------------------------
<template>
Hey ! Welcome to this free salesforce learning platform called: {name}
</template>
---------------------------------------------------
- Defined card inside the template in markup
card.js
---------------------------------------------------
import { api, LightningElement } from 'lwc';

export deafult class card extends LightningElement {
@api 
   name = "Salesforce Kid"
}
---------------------------------------------------
- with @api defined value of name as 'Salesforce Kid'
cardContainer.html
---------------------------------------------------
<c-card></c-card>
---------------------------------------------------
- Called that card component inside cardContainer component markup.
cardContainer.js
---------------------------------------------------
let card = this.template.querySelector("c-card");
card.name = "SFKID";
---------------------------------------------------
- Inside controller with querySelector get the c-card component.
- Then from that card variable reassigned the value as "SFKID"
OUTPUT :
---------------------------------------------------
Hey ! Welcome to this free salesforce learning platform called: SFKID
---------------------------------------------------
- Hence the final output will be with the latest value as SFKID. Cool right ? 😎
4. Import/Export (ECMAScript 6) :
This is the file source to help you to use external helper functions and use it here just like a libraries. 
You can also use your own libraries, not just LWC imports. This is just a pulling outside javascript library inside lwc component.

Like for example when we want to use api, track then we use the syntax as follows:
---------------------------------------------------
import {LightningElement, track, api} OR

//for importing apex class functions
import getAccountList from '@salesforce/apex/accController.getAccountList';

//for importing from external library 
import { flatten } from 'c/jsUtils' ;
---------------------------------------------------
As well as whenever you want to export a single variable or a function then we use export syntax as follows :
---------------------------------------------------
export function flatten(obj, prefix=[], current={}) {......}
---------------------------------------------------

5. Spread Notation (ECMAScript 9) :
- This spread notation is a way of explicitly copying data from one array into another when we are using it.
- It can also be used to recreate array, which updates @tracked variable. 
- Spread actually splited the frontend thing when copying values from one array to other.
SYNTAX :
---------------------------------------------------
this.data = [...result1...result2];
---------------------------------------------------
'...' are used as a spread notation 

6. Slots :
  • Slots is also another web standard.
  • It allows HTML to be passed to the component.
Let's understand this with an example  :

Consider a first greeting component :

greeting.html
---------------------------------------------------
<template>
         He is from: <slot name="country"></slot>
         We called him: <slot name="name"</slot>        
</template>
---------------------------------------------------

In another component define the values.

greetingContainer.html
---------------------------------------------------
<c-greeting>
   <span slot="country"> India </span>
   <span slot="name"> Salesforce Kid</span>
</c-greeting>
---------------------------------------------------

OUTPUT :
---------------------------------------------------
He is from: India
We called him: Salesforce Kid
---------------------------------------------------
So its simply push your content inside using slots.  

7. Promises : 
  • If you think data communication 'Synchronously' then this is for you. 
  • It is nothing but wait for the things to come back and when it will come back then do something with them with this approach it promises that it will wait for the things to come back. 
  • It represents eventually completion and failure of the task.
  • It uses .then() .catch() .finally() to handle promise result.
  • This is just like lightning component that what to do with a response like if success then what to do and if its error then what to do 😊.
Let's understand with an example :
----------------------------------------------------
let kidPromise = new Promise(function (resolve, reject){
      setTimeout(function(){
      resolve('Happy learning');
      }, 2000)
});
---------------------------------------------------

---------------------------------------------------
kidPromise.then(function(result){
     console.log('SalesforceKid said:' + result);
}).catch(reason => {
     console.log('Promise rejected:' + reason);
});

//Console result will be  :
//Console > SalesforceKid said : Happy Learning 
---------------------------------------------------

NOTE: If there are multiple promises then we use Promise.all to handle multiple promises.

The above syntax is as per ECMAScript 6 for a higher version like ECMAScript 8 the syntax is quite different as it supports Async/ Await. But the concept remains the same.

8. String Interpolation (ECMAScript) + Let/Const

In lightning AURA components, we have used concatenation lot of time to join multiple strings. But now we need to change something in the lightning web component.

For Example :
---------------------------------------------------
console.log('string1'+'string2'+'string3');
---------------------------------------------------
Now we need to change our habits and learn something called interpolation.

Let's understand with the help of an example :
---------------------------------------------------
function favouriteBlogs{
let firstBlog = 'Salesforce Official';
const secondBlog = 'Salesforce Kid';

//Please observe the string Interpolation below 
console.log('My favourite blogs are ${firstBlog} and ${secondBlog}');
}
//Console > My favourite blogs are Salesforce Official and Salesforce Kid 
---------------------------------------------------
As you can observe in the above code we need to just use ${firstBlog} instead of maintaining '+'  signs.

Let/Const :
Of course, we are familiar with var in Javascript before, but fortunately/unfortunately now we need to use Let/Const

Let :
  • Whenever you want to reassign the value for any variable then we will define with Let variable. 
  • It also signals that the variable will be used only in the block it's defined in, which is not always the entire containing function.
Const :
  • Whenever you use const then the identifier won't be reassigned further. The value will remain constant.
Cooool  😎 Right !! These 8 javascript web standards are the prerequisites before starting with developing lightning web components. You are ready to go Kid for LWC ☁️⚡️

WOHOOO !! YOU HAVE JUST COMPLETED JAVASCRIPT STANDARDS FOR SALESFORCE LIGHTNING WEB COMPONENT EPISODE
If you like this salesforcekid learning platform please let me know in the Comment section...Also, Share with your salesforce folks wish you all
Happy Learning ☁️⚡️ (Learn. Help. Share.) 😊 

<< PREVIOUS                                    NEXT >>

salesforcekid on google play
Javascript Standards For Salesforce Lightning Web Component (LWC) Javascript Standards For Salesforce Lightning Web Component (LWC) Reviewed by on Rating: 5

7 comments:

  1. wow, good article..

    ReplyDelete
    Replies
    1. Thanks for your valuable time 😊

      Delete
  2. Anonymous6/19/2020

    Nice article. Thank you:)

    ReplyDelete
    Replies
    1. Thank you....

      ⚡️HAPPY LEARNING⚡️

      Delete
  3. Excellent job.. thank you.

    ReplyDelete
    Replies
    1. Glad that it's helping you.....

      ⚡️HAPPY LEARNING ⚡️

      Delete
  4. Great content with respect to LEC beginners :)

    ReplyDelete

HELP !! SHARE !! SUGGEST !!

Powered by Blogger.