JavaScript Basics For Lightning Web Components | Part 1

Telegram logo Join our Telegram Channel
Today I am going to share a few things from modern JavaScript/ES6+. Which will be very useful to you for Lightning Web Component Development.  I will start with some basic stuff like variables and gradually I will explain some complex things, so let's get started.


The let Keyword

Before the let and const keywords, JavaScript only had globally scoped variables and function scoped variables. But with let and const you can define block-scoped variables. Let's demonstrate the difference with an example.

'var' example
for(var i = 0; i<5; i++){
 console.log('i => ' + i);
}
console.log('after for i => ' + i); // i is still accessible here.
/* Expected Output:
> i => 0
> i => 1
> i => 2
> i => 3
> i => 4
> after for i => 5
*/
Now let's try with 'let' instead of var.

'let' example
for(let i = 0; i<5; i++){
 console.log('i => ' + i);
}
console.log('after for i => ' + i); // you get error as 'i' is not defined.
/* Expected Output:
> i => 0
> i => 1
> i => 2
> i => 3
> i => 4
> Uncaught ReferenceError: i is not defined
*/
As you can see the variable defined with 'let' is not accessible outside the 'for' block, an exception is fired.

Variables defined with 'let' are not attached to the 'window' object.
As you know that global variables can be accessed like window.variableName, but this does not apply to the 'let' variables. See below example:
var message = 'hello';
let message2 = 'World';
console.log('message => ' + window.message);
console.log('message2 => ' + window.message2);
/* Expected Output:
> message => hello
> message2 => undefined
*/

The const keyword

The const allows us to define the constants in JavaScript. You cannot change the value once it is assigned. Constant is block scoped.
const message = 'Hello Readers';
console.log('message => ' + message);
message = 'Hello World';
/* Expected Output:
> message => Hello Readers
> Uncaught TypeError: Assignment to constant variable.
*/

Backtick / Template String

You might have used a single quote or double quote for defining the string literals previously but the Template string is a new way of defining strings in Modern JavaScript. Here are some advantages of Backquote or BackTick or Template strings.
  • It allows embedded expressions.
  • It supports multiline strings. 
  • You can add placeholders in the string which will be dynamically replaced by a variable or expression.
  • You can escape the backtick as well.
So let's see some examples.
console.log(`Hello World with Template String!`);

Here is how you can use expressions in template strings.
let message = ` the string that supports multiline
line 1
line 2
`
console.log(`message ${message}`);
/* Output
message  the string that supports multi-line
line 1
line 2
*/

Use mathematical or logical expressions in Template Strings.
let a = 10;
let b = 20;
console.log(`Addition of ${a} and ${b} is ${(a+b)}`);
// Output: Addition of 10 and 20 is 30

console.log(`${a} is less than ${b} : ${a < b}`);
// Output: 10 is less than 20 : true


Advanced Objects Literals

I am sharing the methods to define objects, functions in ES6. To avoid confusion, I will just show the new ES6+ way of doing it.

You can create an empty object like this.
let student = {}

However, you can add the properties directly while creating an object. The below code creates a student object with name and class properties.
let student = {
  name: 'Shree',
  class: 'First',
}

The below code demonstrate the shorthand property names. With this, you can use variables to define object properties.
let name = 'Arnav';
let age = 10;
let student = {
  name,
  age ,
}
console.log(student);

The below code creates a function for the student object, called printName which prints the name of the student on the console.
let name = 'Arnav';
let age = 10;
let student = {
  name,
  age ,
  printName(){
   console.log(`Name => ${name}`);
  }
}
student.printName();
// Output "Name => Arnav"

Computed property names for Objects
I think this is one of the cool features of Modern JavaScript. You can use expressions to create object properties in the square brackets [ ]. The calculated value of that expression will be used as the property name for the object. Let's see the below example.
let propertyName = 'property';
let index = 0;
let object = {
 [propertyName + ++index]: 'value1',
   [propertyName + ++index]: 'value2',
   [propertyName + ++index]: 'value3',
};
console.log(object);
// Output: Object { property1: "value1", property2: "value2", property3: "value3" }
Did you see how the property1, property2, property3 are added to the object using the expression inside [ ]? Isn't it cool?

Note: Object literals are not similar to the JSON, these the methods mentioned above for defining object literals are not valid for JSON.

The Spread Syntax "..."

It uses three dots before the object on which you are applying the spread. The spread syntax allows us to expand the objects into keys or arrays into elements or strings into characters where zero or more elements are expected as an argument to a function or as an element of arrays. Let us see an example.
function addition(a, b, c) {
  return a + b + c;
}

const numbers = [1, 2, 2];

console.log(addition(...numbers));
// expected output: 5

In the above example, you can see how the array of numbers is spread as arguments to the addition function. So you can imagine how the spread is converting an array into comma-separated elements.
Now, lets an example of spread with an object.
let object = {
  prop1: 'value 1',
  prop2: 'value 2'
}
let cloneobject = { ...object, prop3: 'value3' }
console.log(cloneobject);
// expected output: Object { prop1: "value 1", prop2: "value 2", prop3: "value3" }
The object1 from the above code is copied into the new cloneobject, with one additional property prop3.

Using the spread with new keyword
const datefields = [2020, 3, 27];  
const mydate = new Date(...datefields);
console.log(mydate);
// Expected Output: Mon Apr 27 2020 00:00:00 GMT+0530 (India Standard Time)
// Note: zone can change as per your time zone

Concat two arrays
let array1 = [1, 2, 3];
let array2 = [4, 5, 6];

let newarray = [...array1, ...array2];
console.log(newarray);
// Expected Output: [1, 2, 3, 4, 5, 6]
Note: Always use {...object} for objects as objects are not iterable themselves. You can use reduce(), map() or assign() to convert them into iterables.

Feedback

Your feedbacks are really important to me.
I hope this post helped you to learn something new today. Please let me know in the comments box, which features of Modern JavaScript you like the most. Let me know if you want me to cover any specific topics.
More stuff coming up. Till the next time, goodbye.
5 comments:
  1. This content is very help full. Thanks for sharing this artical.

    ReplyDelete
  2. Outstanding blog! I have been trying to find something such as this for a long time now. Thanks!

    ReplyDelete

Hi there, comments on this site are moderated, you might need to wait until your comment is published. Spam and promotions will be deleted. Sorry for the inconvenience but we have moderated the comments for the safety of this website users. If you have any concern, or if you are not able to comment for some reason, email us at rahul@forcetrails.com