Salesforce Lightning: Useful Javascript Tips to Develop Efficient Lightning Components

In previous article we discussed about useful tips and things to use while developing Lightning components. Since Lightning development requires Javascript knowledge to perform various tasks on client side, so lets discuss about some Javascript useful tips and tricks to use when using Javascript in Lightning controllers. This article would be useful for developers who are migrated form Visualforce to Lightning and got little chance to work on Javascript during development on Visualforce framework.

Javascript is a multi-paradigm and imperative functional language. It has behavior of functional programing language and concepts of object-oriented programing. It means that you can create first class objects in Javascript and later change is properties and state in run-time.

Above properties provide super powers to Javascript but can cause great issues if not implemented correctly. Below are few things which should be considered when using Javascript:-

1. Type conversion v/s Equality ( === vs == )

In Javascript we have ‘===’ equality comparison operation in addition to ‘==’. It is good practice to use ‘===’ instead of ‘==’. Because double equal comparison can cause weird behavior in programing because it convert the type of data if it is not equal to right hand side data type. And programmer can never figure about why the value is true? Some examples:-

Using the === operator

true === 1; //false
"10" === 10;  //false
1 === [1]; //false

Using the == operator

true == 1; //true
"10" == 10;  //true
1 == [1]; //true

2. Concept of “undefined”

Javascript has additional NULL type which is “undefined”. Developer must always handle “blank double quotes (”), null (there in no NULL in javascript) and “undefined”.

'' == undefined; //false
undefined == '' //true
var a; console.log(a===undefined); //true
var a; console.log(a===null); // false

Comparing null with undefined using double equal (==) always return true but what if you get blank value instead of null/undefined. It will again cause a unexpected behavior.

3. Floating point Precision

If there is need to calculating decimal, it must be used with function `toFixed()’ or `toPrecision()`. Reason:-

Look at following post on Stackexchange salesforce. Apex Division Losing Precision. This applies to Javascript as well. Lets take the following example:-

0.1 + 0.2 === 0.3 //#1 false

Because it is actually 0.30000000000000004. Not that `toPrecision` and `toFixed` return `String` not the number type.

4. Use for loop instead of for-in

for-in loop like below we do not have control over iteration and calculation behind. IT can eat more processing time depending on object type.

var total = 0;
var items = new Array(4);
for (var i in items) {  
    total += items[i];  
}

We can use the same in for loop in more optimized and controlled way:-

var total = 0;
var items = new Array(4);
for (var i = 0, len = items.length; i < len; i++) {  
    total += arrayNumbers[i];  
}

In above example we have defined and calculated length in for-loop itself which will result into faster execution. Below is JSPerf test of both where iteration done adding value 1000 times in Chrome.

5. Use Map() to avoid duplicates

Instead of writing own algorithm to avoid duplicates in Array/List. Use Map() function. It works same as Apex Map, key and value pair. Below is the example:-

var myMap = new Map();
myMap.set('a', 1);
myMap.set('b', 2);
myMap.set('c', 3);
myMap.set('d', 4); // will be overriden
myMap.set('d', 5); // duplicate
for (var [key, value] of myMap) {
  console.log(key, value);
}

//a 1
//b 2
//c 3
//d 5

Keeping above things while developing code we can avoid various issues in Javascript and make our code efficient when the code run on client-side. Lighting components have client side controllers so, Visualforce developers migrating to Lighting must understand best practices we should implement in code.

Useful links:-

  1. Learn JS
  2. Lightning Tips: Transition to Lightning Framework
  3. Stay tuned on Salesforce Stackexchange
Advertisements

Lightning Framework: Transition your Salesforce implementation to Lightning Components Framework

Salesforce Lightning

Salesforce Lightning Component Framework is a recent framework launched by Salesforce. It is based on open-source Aura framework which is Javascript based.

Main advantages of Lightning framework is it is light weight, client-side, out of the box responsive and efficient. It is based on event-driven architecture where UI events are handled by Javascript handlers.

Now the question comes is how we can leverage its advantages and what are the things we must consider to move the implementation to Lightning frameworks. One of the major problem while moving to Lightning is we have already functional Visualforce pages and those are completely different in architecture than Lighting framework. So lets find out some important things we should consider when taking decision of moving to Lightning framework or developing a new Lightning component.

How to begin

The very obvious answer is Salesforce Trailhead. To start, the recommended Trailhead module is “Lightning Components Basics“. This will provide basic idea of developing application using Aura Lightning framework, its structure and essential code syntaxes.

This is Javascript so Client-Side

Lightning framework is based on open-source Aura framework which is Javascript based. Javascript code runs on client machine. It does not require server to perform operation until and unless we are doing some Ajax based call to fetch data. If there is Javascript is base it means only data we need from server in most of the cases, that’s all!

In Lightning component_name.js file is client-side and Apex controller is our Server.

Leveraging this capability, code developed in Javascript become highly efficient. And we can distribute various tasks between client machine and server. So, plan in way what operation we should perform by Server process which tasks should happen on client side. Generally, light weight task should happen on client-side. For example: If we need to add a few values and output the sum then we should perform that task in Lightning controller. And if we want to aggregate 1000 of values then it is better to perform it on Apex controller.

Note: Each call to apex class though component is Asynchronous. In other words, it follows callback mechanism.

It is Case-Sensitive

Apex is case-insensitive which gives us freedom to write code without taking care of alphabet case. Lighting controller have just opposite to it. It is case-sensitive. A variable defined with name “motorVehicle” is different from “MotorVehicle”. So, care should be taken while writing Lighting controller code.

Make sure we code considering The Locker Service

This is recently introduced security layer to prevent un-authenticated changes to Lightning component. Because Lightning design is component based and there can be multiple components from different vendors so, a security layer must be available so, components don’t hack into other components and inject code.

To prevent un-authenticated code injection, locker-service is introduced. It forces the Lightning component to work in its scope. Attempt to modify any element outside of component boundary will result into “Access Denied” exception.

Best way to avoid such issues is always use methods provided by Lighting framework api. There would be javascript experts who can create magic, but in Lighting, it is better to follow Lighting Framework provided methods.

Lightning application are set of multiple components and those components can interact with registered events and their handlers. Set of components create a Lightning application. We can say it like a Visualforce page created from several Visualforce components. But Lightning is client side where Visualforce is server side.

Understand the SLDS (Salesforce Lightning Design System) CSS

SLDS is a CSS library to help us getting consistent user interface same as Salesforce Lightning view. This recommended CSS to use when we are developing code in Salesforce even in case of Visualforce. It can be downloaded from SLDS website.

Note that Lightning components don’t need to import this CSS. It is available by default. Here is Trailhead module named “Lighting Design System” to understand of SLDS system.

SLDS is one of the way to convert the Visualforce page in SLDS look alike. Instead of inventing own CSS, use SLDS css. However, it is a huge challenge in converting Visualforce tags into SLDS compatible HTML elements specially, <apex:pageblock/> and <apex:PageBlockTable/>.

Unit Testing

Right now Salesforce has not given any standard tool to perform unit testing on client-side controllers. However, there is a built-in unit testing framework for Aura, the technology on which Lightning components are based but not exposed yet. So, we have to make sure that:-

Variables and methods are used is in same case as it was declared.

If there is unexpected condition don’t hesitate to throw errors using

throw Error(' Message');

Javascript has try-catch as well. Utilize then to log any activity which would be helpful for developer.

try {
    Block of code to try
}
catch(err) {
    Block of code to handle errors
}

It is asynchronous so make sure declared variables don’t go out of scope in code and result in undefined errors which are hard to debug.

The Deployment

Lighting components are saved in metadata folder named “Aura” which contain the component, controller, helper etc. Controller and helper are Javascript files having .js extension. We can retrieve or deploy Lightning components by defining AuraDefinitionBundle type and name of the component as member in package.xml.

“aura” folder contains all components which further sub-divided based on component name.

In summary, the basic need to get into Lightning development is understanding of Javascript concepts. It does not mean to be a Javascript expert as there are <aura/> tags to make lot of thing easy. In comparison to Visualforce tags those aura tags are straightforward. But because lighting components are quick responsive and asynchronous so, win over many limitations of Visualforce.

Resource for the new Lightning experience

1. Get started with: https://www.linkedin.com/pulse/lightning-experience-create-pixel-perfect-visualforce-ashwani-soni?trk=mp-reader-card

2. Design Guide: http://www.lightningdesignsystem.com

3. Lightning Experience FAQs: https://developer.salesforce.com/page/Lightning_Experience_FAQ

4. Twitter: @SalesforceUX Stay tuned!