Modern JavaScript

Originally named as “LiveScript” but later launched as JavaScript, owing to the popularity of the technology at that time, it has become one of the most popular programming languages.
JavaScript has been evolving over the last two decades. However, until 2015, JavaScript did not have too many enhancements. The JavaScript version most developers are familiar with - ES5) - was published in 2009.
Over the last few years, JavaScript has evolved rapidly and the version that we are using has become an old-school version (most of the developers call it “The Dark Ages” of the JS!).
So let’s get up to the speed quickly and learn some cool new features of ECMAScript 2015+ also popularly known as ES6+.

let

In the old-school, we were using ‘var’ to declare a variable. That has a huge loophole in the architecture and its behavior. Sometimes it becomes a bottleneck for the developers because ‘var’ does not support block scope. To understand the block scope, see the following piece of script:

var x = true;

if(1 == 1){
    var x = false;
    console.log(x);
}

console.log(x);
                                        
The above script will show ‘false’ for both of the console logs. Because ‘var’ will not consider the ‘if’ block scope.
To fix this issue ES6 has introduced a new keyword ‘let’. This keyword limits the scope to the block, so this eliminates any ambiguity in the code and the script written becomes bug-free.
So below script will show ‘false’ for the console in the ‘if’ block and the outer console will show ‘true’.

let x = true;

if(1 == 1){
    let x = false;
    console.log(x);
}

console.log(x);                                    

const
const keyword usage is similar to ‘let’ and it also supports the block scope. This keyword is used to define the constant. Value cannot be reassigned to the variable defined as ‘const’, so it needs to be initialized always, otherwise it will give an error.

Template Literals

To create a dynamic string message, you must be using the ‘+’ operator to concatenate the strings. See the below script to get more insight.

const contactName = "Ashish Sharma";
let errorMessage = "Please enter address for " + contactName;
                                        
This is the most commonly used feature of the dark ages JS and does not look so cool. It is prone to bugs in the script also as proper syntax and concatenation of many variables are required.
Template literals provide a way to create this kind of string in a very simple and bug-free way, look at the below script and get rid of ‘+’ operator.

const contactName = "Ashish Sharma";
let errorMessage = `Please enter address for ${contactName}`;
                                        
Notice that we are using `(backtick) character instead of a single quote(‘) or double quote (“) in the above script and it can abolish the need of character escaping also.
A better way to define a function
Till now we were defining the JS functions like this:

var concat = function(a,b,c){
    return a + ',' + b + ','  + c;
}
                                        
Now in modern JS, there is a whole new way to define functions that are inspired by lambda expression in C#. So here we go:

let concat = (a,b,c) => a + ',' + b + ','  + c;
                                        
Isn’t it much simpler! You can add curly braces and ‘return’ keyword if your function is a complex one and has more than 1 line like below:

let concat = (a,b,c) => {
    let result = "";

    if(a){
        result += a;
    }

    if(b){
        result += (result != "" ? "," : "") + b;
    }

    if(c){
        result += (result != "" ? "," : "") + c;
    }

return result;
}
                                        
There is 1 more important advantage that lambda expression provides, generally when we define a function in the old school way, ‘this’ keyword is rebind for each nested method, look at the below function for more understanding:

let calculate = {
    inputs: [1,2,5,6],
    result: 0,

    add: function(){
    this.result = 0;

    this.inputs.forEach(function(input){
        this.result += input;
            });
    }
}
                                        
The above function will show 0 in the result as a forEach function will not recognize this.result as it rebinds the ‘this’ keyword for itself. Lambda expression fixes this issue and unlike the normal function, it does not rebind the ‘this’ keyword.

let calculate = {
    inputs: [1,2,5,6],
    result: 0,

    add: function(){
    this.result = 0;

    this.inputs.forEach((input) => {
        this.result += input;
            });
    }
}
                                        
The above function will work in the correct way and will show 14 in the result.
Destructuring
Destructuring enables developers to fetch the properties from an object or elements from the array in a better way.
Let’s say we have the following object:

const contact = {
    firstName: 'Ben',
    lastName: 'Newman',
    phone: 'xxxxxxxxxx'
}
                                        
Now to fetch the firstName and lastName properties from the contact object, most of the JS developers use the below syntax:

const firstName = contact.firstName;
const lastName = contact.lastName;
                                        
Using destructuring syntax, this task becomes much simpler and less prone to errors.

const {firstName, lastName} = contact;
                                        
Rest Parameters
Rest parameter is a modern way to define the n number of remaining parameters for a function. Function definition requires three dots(...) to define a rest parameter. Look at the below function:

let calculate = function(a, b, ...numbers){
    return a +b + (numbers[0] * numbers[1] * numbers[2]);
}

calculate(2, 3, 10, 23, 45);
                                        
Modern JS (ES6+) has introduced many other features for JavaScript development but the above-mentioned features are used in most of the script (almost 75% of the script). So, start using these cool features and show the world an upgraded version of yourself.

Comments

Popular posts from SFDC Drona

Retrieve IP Address for the Guest Users in Lightning Community

Email Alert to Parent object's email field without apex

Incremental/delta data export using command line data loader