Essential JavaScript skills required for Lightning Web Components

Have you been thinking about what the ES6 concepts are that are required to learn to shine in Lightning Web Components? If yes! then this article is for you.

You could have surfed over the internet to gain the knowledge of ES6 topics here and there depending on your development needs, but here you are going to gain the most useful skills of JavaScript ES6 features in one place. Through this article, we have given more importance to example codes. Let’s get in,

1. Var vs Let vs Const

Var

Let us discuss some points about Var keyword here:

We expect that ‘James’ will be printed on the console, but since the variable name is global scoped, the variable name outside the if block has been overridden by the variable inside the if block. So, we got the output ‘Warner’ on the console.    Seems no issues right!!     But the problem is when we need to use the same variable name in multiple places, it forces us to use different variable name every time and it leads to unnecessary memory allocation.

Another problem is hoisting, let’s see what it is,

You can see that it didn’t threw any error when we access the age variable before declaration. But wait!! Why it prints undefined in the console even though It didn’t throw any error?

What JavaScript engine does is as below,

variable age is hoisted at the top of the scope but note that variable is only hoisted not the value20’. That’s why it prints undefined on the console.

It allows us to redeclare the same variable name in the same scope, but it takes the most recent value.

Let

Let is used to declare the variable in block scope and it doesn’t allow us to use the variable before declaration. Let’s see an example

You can see that the variable name is not overridden, since we declared the name as a block scoped variable so the variable inside the if block doesn’t have access to the variable outside the If block.

It solves the hoisting issue; we can see how it is.

Now, see it throws error when we access the age variable before declaration. It says age is not defined.

Let variables cannot be redeclared in the same scope.

Since the variable education is already declared, it throws error as above.

Const

It is same as let keyword, but the difference is that it does not allow you to change the value once it is declared.

See, when we try to change the value, it throws a TypeError.

Wait!! Here is one catch. Above example is only for Primitive variables. What about the Object?

Let’s see what happens when we change the value of the property in an Object.

In the above example, we were able to modify the value of the company property from ‘MST’ to ‘other’, and we could do it successfully without any error. How!!?

Yes! We can modify the value of the properties, but we cannot reassign the reference to the new Object. See the example below,

If you want the Object to immutable, use Object.freeze() method.

2. Undefined vs null

One of the confusing topics in JavaScript is Undefined and Null. Look into the below table,

UndefinedNull
If nothing is assigned to a variable Assigned explicitly
Typeof is undefinedTypeof is Object
Undefined == null returns trueUndefined === null returns false

Example for undefined.

Variable length is uninitialized, so it is automatically assigned a value to undefined.

Typeof length is also undefined.

Comparing undefined and null with double-equal to returns true.

Null is saying that there is no value.

Examples for Null,

If you want to assign Null to a variable, you must do it explicitly.

Typeof null is an Object,

Comparing undefined and null with triple-equal to returns false since it compares the values and type of the value.

3. Arrow function

ES6 introduced the Arrow function. It is a shorter function syntax.

The main difference between the Regular function and Arrow function is scope of ‘THIS’ keyword.

In Regular functions, THIS keyword represents the Object that called the function, which could be the window, the document, a button or whatever.

In Arrow function, THIS keyword represents the Object that defined the arrow function.

If you have a function inside another function, like below, scope of THIS will be lost. See below code,

Inside setTimeout, we are passing another function and print the id property. But you can see, we got undefined instead of 20. This is loosing scope. Before Arrow function, we would use the bind() method to attach the scope of the current object. In Arrow function, it is very simple. It always refers to the Object that defined the function.

If you don’t have an arguments and have only one statement inside the function, then you can omit the brackets and simply put underscore and also omit the function opening and closing brackets. It is only one line of code. This is very simple!! Isn’t it.

Or you can do it like below

4. Spread Operator

The consecutive three ”” dots in Javascript has a special meaning and it is called as Spread Operator. Let’s see how we can utilize this.

i) Expanding Arrays – Content gets expanded and throw out of an Array

You can see that ‘Hello’ and ‘World’ has been threw out of an Array

ii) Expanding String – Convert string into an Array of Characters

Its pretty easy right?

iii) Combining Arrays – Combine two or more arrays or add value to an existing array

Result array contains both of the values from arr1 and arr2. Note that if you print arr1 again, its not mutated. Yes! Spread operator always creates a new copy.

iv) Combining Objects – Combine Object or add value to an Object

Same as the array , objects can also be combined using Spread operator.

But here is one catch…

If both objects have the same key, then the value will be updated

Note that ‘profession’ key’s value has been changed to ‘Quality Analyst’, since when you combine the objects with same key, then the existing value will be overriden with new value.

Note: Have you used pop(), push() and slice(). These are the methods that will modify the original array and that is very dangerous thing. Spread operator is our life saver to avoid using those methods.

5. Destructuring


Destructuring is the concept in Javascript that has been introduced in ES6. It is a special syntax that allows us to UPACK the Arrays and Objects into a bunch of variables. We have two types,

i) Array destructuring

Let’s see in an example

If you want to assign these values to a separate variables, you have to do like before destructuring,

But now we have array destructuring and it is very simple as below

Now, we got a separate variables ‘firstname’ and ‘lastname’ with corresponding values.

ii) Object destructuring

Let’s see an example. You have an Object called person

If you want to assign value of properties into the sperate variables, you have to do it before object destructuring,

Same thing could be achieved by Object destructuring.

It is pretty simpler than the traditional method. Here is one thing to note that the destination variable name must be same as the property name. for example, name property value could not be stored in some other name except name.

6. String Interpolation

Are you tired of concatenating string and variables in String Template? Don’t worry!!

String interpolation allows you to embed expressions in string template without concatenate anything. It uses back tick ( ` `) rather than using single or double quotes.

Ex:

You can see that variable company is wrapped inside ${}. You can also use expressions like below.

7. Import and Export modules

There are several ways to export modules in another javascript modules:

1) Export members individually

2) Export members together

3) Export members with alias

4) Default export

Let’s say we have util.js file that has utility functions called add,sub,mul,div, and we are going to utilze these functions app.js

i) Export members individually

util.js

export function add(a,b){

    console.log(a+b);

}

export function sub(a,b){

    console.log(a-b);

}

export function mul(a,b){

    console.log(a*b);

}

export function div(a,b){

    console.log(a/b);

}     

App.js

import { LightningElement, track } from ‘lwc’;

import { add,sub} from ‘./util.js’;

export default class App extends LightningElement {

    connectedCallback(){

        add(6,3);

        sub(6,3);

    }

}

ii) Export members together

util.js:

function add(a,b){

    console.log(a+b);

}

function sub(a,b){

    console.log(a-b);

}

function mul(a,b){

    console.log(a*b);

}

function div(a,b){

    console.log(a/b);

}

export {add,sub,mul,div};

App.js

import { LightningElement, track } from ‘lwc’;

import { add,sub} from ‘./util.js’;

export default class App extends LightningElement {

    connectedCallback(){

        add(6,3);

        sub(6,3);

    }

}

iii) Export members with alias

util.js:

function add123(a,b){

    console.log(a+b);

}

function sub123(a,b){

    console.log(a-b);

}

function mul123(a,b){

    console.log(a*b);

}

function div123(a,b){

    console.log(a/b);

}

export {add123 as add,sub123 as sub,mul123 as mul,div123 as div};

app.js

import { LightningElement, track } from ‘lwc’;

import { add,sub} from ‘./util.js’;

export default class App extends LightningElement {

    connectedCallback(){

        add(6,3);

        sub(6,3);

    }

 }

iv) Default export

Only one default export per module is allowed

util.js

export default function add(a,b)

{

    console.log(a+b);

}

app.js

import { LightningElement, track } from ‘lwc’;

import add from ‘./util.js’;

export default class App extends LightningElement {

    connectedCallback(){

        add(6,3);

                }

}

Import modules

i)Import with alias

util.js:

export function add(a,b)

{

    console.log(a+b);

}

app.js:

import { LightningElement, track } from ‘lwc’;

import {add as addition} from ‘./util.js’;

export default class App extends LightningElement {

    connectedCallback(){

        addition(6,3);

    }

 }

ii)Import using * with alias

util.js

export function add(a,b){

        console.log(a+b);

}

export function sub(a,b){

        console.log(a-b);

}

app.js

import { LightningElement, track } from ‘lwc’;

import {* as math} from ‘./util.js’;

export default class App extends LightningElement{

        connectedCallback(){

                        math.add(7,8);

                        math.sub(6,4);

        }

}

8. Promise

Did you know  Javascript is a single threaded programming language which makes it blocking. Before Promise, developer would use callback methods for doing asynchronous programming. But exessive use of callback methods would cause callback hell issue, that is callback inside another callback and it grows into big callback chain.

Promise is the concept which makes your job easy to write complicated code in async programming. It also removes the callback hell issue.

Promise is an Object which has the ‘then’ and ‘catch’ methods on it. One of these methods gets called when the promise returns a value or error. Let’s understand the concept through an example,

Here, we call resolve callback method to resolve the promise. If it is resolved, then the then method will execute, if rejected, catch method will execute. Let’s see that also.

Here, you can note that in the below example, promise has catch method and then method has got an error callback. You may get a confusion, Any idea?. which one will execute?. Actually, error callback function in then method will take precedence over the catch method, if you have both error handling method. See below,

 You can note that the catch method has got two console not printed.

9. Async and Await

There is special syntax to work with Promises in a more comfortable fashion is ‘async/await’.

The word ‘async’ before a function means one simple thing; a function always returns a promise.

The keyword ‘await’ makes Javascript wait until that promise settles and returns its result. ‘await’ only works inside the async function.

See the below example,

Why do we have async/await when we have promise is sometimes we have to execute the asynchronous code in a synchronous way.

10. querySelector() and querySelectorAll()

This method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.

In this example, the first element in the document with the class “myclass” is returned

A more complex selector:

Selectors can also be really powerful, as demonstrated in the following example. Here, the first <input> element with the name “login” (<input name=”login”/>) located inside a <div> whose class is “user-panel main” (<div class=”user-panel main”>) in the document is returned

querySelectorAll() returns the list of elements that matches the specified selector, or group of selectors. It returns a NodeList object.

To obtain a NodeList of all of the <p> elements in the document

This example returns a list of all <div> elements within the document with a class of either note or alert

There are lot to learn about javascript, but in this aritcle we just introduced the fundamental concepts to learn Lightning Web Components.

References:

https://www.freecodecamp.org/news/var-let-and-const-whats-the-difference/#:~:text=var%20declarations%20are%20globally%20scoped%20or%20function%20scoped%20while%20let,be%20updated%20nor%20re%2Ddeclared.

https://codeburst.io/javascript-null-vs-undefined-20f955215a2

https://javascript.info/promise-basics

https://javascript.info/async-await

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

https://javascript.info/import-export

https://coursesweb.net/javascript/queryselector-queryselectorall

About MST

At MST Solutions our cornerstone is to adapt, engage and create solutions which guarantee the success of our clients. The talent of our team and experiences in varied business verticals gives us an advantage over other competitors.

Recent Articles

Work with us.

Our people aren’t just employees, they are key to the success of our business. We recognize the strengths of each individual and allow them time and resources to further develop those skills, crafting a culture of leaders who are passionate about where they are going within our organization.