Tuesday, December 10, 2019

JavaScript Essentials for Lightning Aura/Web Component


If you are going to start with Lightning Aura Component or Lightning Web Component development, I assume you are good with JavaScript. Anyway, I am going to share something which I feel you must know before jumping to component development.

In this blog I will talk about some of the most required JavaScript concepts you should know before you start building your beautiful and robust Lightning Aura/Web component.

So, without wasting any time let’s get started.

JavaScript THIS.
Global Context
In the global execution context (outside of any function), this refers  to the global object whether in strict mode or not.
// In web browsers, the window object is also the global object:
console.log(this === window); // true

a =
37;
console.log(window.a); // 37

this.b = "MDN";
console.log(window.b)  // "MDN"
console.log(b)         // "MDN"

Function context
Inside a function, the value of this depends on how the function is called.
Since the following code is not in strict mode, and because the value of THIS is not set by the call, this will default to the global object, which is WINDOW in a browser.

function f1() {
 
return this;
}
// In a browser:
f1() ===
window; // true

In strict mode, however, the value of THIS remains at whatever it was set to when entering the execution context, so, in the following case, THIS will default to undefined:
function f2() {
  'use strict'; // see strict mode
 
return this;
}
f2() ===
undefined; // true

As a DOM event handler

When a function is used as an event handler, its THIS is set to the element the event fired from (some browsers do not follow this convention for listeners added dynamically with methods other than addEventListener).

// When called as a listener, turns the related element blue
function bluify(e) {
 
// Always true
 
console.log(this === e.currentTarget);
 
// true when currentTarget and target are the same object
 
console.log(this === e.target);
 
this.style.backgroundColor = '#A5D9F3';
}

// Get a list of every element in the document
var elements = document.getElementsByTagName('*');
// Add bluify as a click listener so when the
// element is clicked on, it turns blue
for (var i = 0; i < elements.length; i++) {
  elements[i].addEventListener(
'click', bluify, false);
}
In an Inline event handler
When the code is called from an inline on-event handler, its this is set to the DOM element on which the listener is placed:

<button onclick="alert(this.tagName.toLowerCase());">
  Show this
</
button>
The above alert shows button. Note however that only the outer code has its THIS set this way:

<button onclick="alert((function() { return this; })());">
  Show inner this
</
button>
In this case, the inner function's THIS isn't set so it returns the global/window object (i.e. the default object in non–strict mode where this isn't set by the call).

Type Conversion vs Equality

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 programming because it converts the type of data if it is not equal to right hand side data type. And programmer can never figure why the value is true ?

Using the === operator

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

Using the == operator

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

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 an unexpected behavior.

concept of CALLBACKS

Callbacks in JavaScript are functions that are passed as arguments to other functions. This is a very important feature of asynchronous programming, and it enables the function that receives the callback to call our code when it finishes a long task, while allowing us to continue the execution of the code.

For example:

var callback = function() {
   
console.log("Done!");
}
setTimeout(callback,
5000);

This code waits 5 seconds and prints out "Done!" when the 5 seconds are up. Note that this code will not work in the interpreter because it is not designed for handling callbacks.

It is also possible to define callbacks as anonymous functions, like so:

setTimeout(function() {
   
console.log("Done!");
},
5000);

Like regular functions, callbacks can receive arguments and be executed more than once.

Javascript Important FUNCTIONS
  • Get
  • Set
  • Push
  • Unshift
  • Splice
Get & Set
These are useful and common patterns for working with attribute values in JavaScript. These are used in client side controller (js controller) get the value from component attribute.

Example:

I have an Aura Attribute - firstName

for use attribute value in javaScript code you must use cmp.get()
({
getName :
function(cmp, event, helper) {
var myName = cmp.get("firstName");
alert(myName);
  }
})
Push

The push() method adds new items to the end of an array, and returns the new length. The new item(s) will be added at the end of the array. This method changes the length of the array.

Example:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.
push("Kiwi");

Unshift

The unshift() method adds new items to the beginning of an array, and returns the new length. This method changes the length of an array.

Example:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift(
"Kiwi");
Splice

The splice() method adds/removes items to/from an array, and returns the removed item(s). This method changes the original array.

Example:

At position 2, add the new items, and remove 1 item:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(
2, 1, "Lemon", "Kiwi");

Parameter
Description
index
Required. An integer that specifies at what position to add/remove items, Use negative values to specify the position from the end of the array
howmany
Optional. The number of items to be removed. If set to 0, no items will be removed
item1,...,itemX
Optional. The new item(s) to be added to the array

There are few more things which will be specific to Lightning web Component
that I will cover in next blog.

I hope you guys find this helpful.


Thank you !! Keep Coding.


3 comments: